Question

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 >.

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?

Was it helpful?

Solution

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.

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);

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.

OTHER TIPS

Lack of this behavior is unacceptable.

A standalone unescaped > is invalid XML.
XElement is designed to produce valid XML.

If you want to get the unescaped content of the element, use the Value property.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top