本文介绍了如何阻止XElement.Save转义字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用信息填充 XElement ,并使用 XElement.Save(path)方法将其写入xml文件.在某些时候,结果文件中的某些字符将被转义-例如,> 变为& gt .

I'm populating an XElement with information and writing it to an xml file using the XElement.Save(path) method. At some point, certain characters in the resulting file are being escaped - for example, > becomes >.

这种行为是不可接受的,因为我需要在XML中存储包含> 字符作为密码一部分的信息.如何在不逃脱XElement对象的原始"内容的情况下将它们写入XML?

This behaviour is unacceptable, since I need to store information in the XML that includes the > character as part of a password. How can I write the 'raw' content of my XElement object to XML without having these escaped?

推荐答案

XML规范通常允许> 看起来不转义. XDocument 可以安全播放并对其进行转义,尽管它出现在并非严格要求转义的地方.

The XML specification usually allows > to appear unescaped. XDocument plays it safe and escapes it although it appears in places where the escaping is not strictly required.

您可以对生成的XML进行替换.请注意 http://www.w3.org/TR/REC-xml#syntax,如果这导致任何]]> 序列,则XML将不符合XML规范.此外, XDocument.Parse 实际上将拒绝此类XML,但字符数据中不允许出现错误']]>'."

You can do a replace on the generated XML. Be aware per http://www.w3.org/TR/REC-xml#syntax, if this results in any ]]> sequences, the XML will not conform to the XML specification. Moreover, XDocument.Parse will actually reject such XML with the error "']]>' is not allowed in character data.".

XDocument doc = XDocument.Parse("<test>Test&gt;Data</test>");
// Don't use this if it could result in any ]]> sequences!
string s = doc.ToString().Replace("&gt;", ">");
System.IO.File.WriteAllText(@"c:\path\test.xml", s);

考虑到任何符合规范的XML解析器都必须支持& gt ,因此我强烈建议修复用于处理程序XML输出的代码.

In consideration that any spec-compliant XML parser must support &gt;, I'd highly recommend fixing the code that is processing the XML output of your program.

这篇关于如何阻止XElement.Save转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 06:10