My application generates XML using XmlDocument. Some of the data contains newline and carriage return characters.
When text is assigned to an XmlElement like this:
e.InnerText = "Hello\nThere"; The resulting XML looks like this:
<e>Hello There</e> The receiver of the XML (which I have no control over) treats the new-line as white space and sees the above text as:
"Hello There" For the receiver to retain the new-line it requires the encoding to be:
<e>Hello
There</e> If the data is applied to an XmlAttribute, the new-line is properly encoded.
I've tried applying text to XmlElement using InnerText and InnerXml but the output is the same for both.
Is there a way to get XmlElement text nodes to output new-lines and carriage-returns in their encoded forms?
Here is some sample code to demonstrate the problem:
string s = "return[\r] newline[\n] special[&<>\"']"; XmlDocument d = new XmlDocument(); d.AppendChild( d.CreateXmlDeclaration( "1.0", null, null ) ); XmlElement r = d.CreateElement( "root" ); d.AppendChild( r ); XmlElement e = d.CreateElement( "normal" ); r.AppendChild( e ); XmlAttribute a = d.CreateAttribute( "attribute" ); e.Attributes.Append( a ); a.Value = s; e.InnerText = s; s = s .Replace( "&" , "&" ) .Replace( "<" , "<" ) .Replace( ">" , ">" ) .Replace( "\"", """ ) .Replace( "'" , "'" ) .Replace( "\r", "
" ) .Replace( "\n", "
" ) ; e = d.CreateElement( "encoded" ); r.AppendChild( e ); a = d.CreateAttribute( "attribute" ); e.Attributes.Append( a ); a.InnerXml = s; e.InnerXml = s; d.Save( @"C:\Temp\XmlNewLineHandling.xml" ); The output of this program is:
<?xml version="1.0"?> <root> <normal attribute="return[
] newline[
] special[&<>"']">return[ ] newline[ ] special[&<>"']</normal> <encoded attribute="return[
] newline[
] special[&<>"']">return[ ] newline[ ] special[&<>"']</encoded> </root> Thanks in advance. Chris.