我的应用程序使用XmlDocument生成XML。其中一些数据包含换行符和回车符。
当将文本分配给XmlElement时,如下所示:
生成的XML如下所示:
接收XML的程序(我无法控制)将换行符视为空格,因此将上述文本视为:
如果数据应用到XmlAttribute,换行符会被正确编码。
我尝试使用InnerText和InnerXml将文本应用于XmlElement,但两者的输出结果相同。
是否有办法使XmlElement文本节点以它们的编码形式输出换行符和回车符号?
以下是一些演示问题的示例代码:
这个程序的输出是:
当将文本分配给XmlElement时,如下所示:
e.InnerText = "Hello\nThere";
生成的XML如下所示:
<e>Hello
There</e>
接收XML的程序(我无法控制)将换行符视为空格,因此将上述文本视为:
"Hello There"
如果接收方想要保留换行符,需要使用以下编码:
<e>Hello
There</e>
如果数据应用到XmlAttribute,换行符会被正确编码。
我尝试使用InnerText和InnerXml将文本应用于XmlElement,但两者的输出结果相同。
是否有办法使XmlElement文本节点以它们的编码形式输出换行符和回车符号?
以下是一些演示问题的示例代码:
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" );
这个程序的输出是:
<?xml version="1.0"?>
<root>
<normal attribute="return[
] newline[
] special[&<>"']">return[
] newline[
] special[&<>"']</normal>
<encoded attribute="return[
] newline[
] special[&<>"']">return[
] newline[
] special[&<>"']</encoded>
</root>
事先感谢您的帮助。 Chris。