c# - Escaping new-line characters with XmlDocument -
my application generates xml using xmldocument. of data contains newline , carriage return characters.
when text assigned xmlelement this:
e.innertext = "hello\nthere";
the resulting xml looks this:
<e>hello there</e>
the receiver of xml (which have no control over) treats new-line white space , sees above text as:
"hello there"
for receiver retain new-line requires encoding be:
<e>hello
there</e>
if data applied xmlattribute, new-line encoded.
i've tried applying text xmlelement using innertext , innerxml output same both.
is there way xmlelement text nodes output new-lines , carriage-returns in encoded forms?
here sample code demonstrate 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 = d.createattribute( "attribute" ); e.attributes.append( ); a.value = s; e.innertext = s; s = s .replace( "&" , "&" ) .replace( "<" , "<" ) .replace( ">" , ">" ) .replace( "\"", """ ) .replace( "'" , "'" ) .replace( "\r", "
" ) .replace( "\n", "
" ) ; e = d.createelement( "encoded" ); r.appendchild( e ); = d.createattribute( "attribute" ); e.attributes.append( ); a.innerxml = s; e.innerxml = s; d.save( @"c:\temp\xmlnewlinehandling.xml" );
the output of 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.
how using httputility.htmlencode()
?
http://msdn.microsoft.com/en-us/library/73z22y6h.aspx
ok, sorry wrong lead there. httputility.htmlencode()
not handle newline issue you're facing.
this blog link out, though
http://weblogs.asp.net/mschwarz/archive/2004/02/16/73675.aspx
basically, newline handling controlled xml:space="preserve"
attribute.
sample working code:
xmldocument doc = new xmldocument(); doc.loadxml("<root/>"); doc.documentelement.innertext = "1234\r\n5678"; xmlattribute e = doc.createattribute( "xml", "space", "http://www.w3.org/xml/1998/namespace"); e.value = "preserve"; doc.documentelement.attributes.append(e); var child = doc.createelement("child"); child.innertext = "1234\r\n5678"; doc.documentelement.appendchild(child); console.writeline(doc.innerxml); console.readline();
the output read:
<root xml:space="preserve">1234 5678<child>1234 5678</child></root>
Comments
Post a Comment