我的应用程序使用 XmlDocument 生成 XML。一些数据包含换行符和回车符。
当像这样将文本分配给 XmlElement 时:
e.InnerText = "Hello\nThere";
Run Code Online (Sandbox Code Playgroud)
生成的 XML 如下所示:
<e>Hello
There</e>
Run Code Online (Sandbox Code Playgroud)
XML 的接收者(我无法控制)将换行符视为空白,并将上述文本视为:
"Hello There"
Run Code Online (Sandbox Code Playgroud)
为了让接收者保留换行符,它需要编码为:
<e>Hello
There</e>
Run Code Online (Sandbox Code Playgroud)
如果数据应用于 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 = …Run Code Online (Sandbox Code Playgroud)