使用 XmlDocument 转义换行符

Chr*_* C. 5 c# xml xmldocument .net-2.0

我的应用程序使用 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&#xA;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 = s;
e.InnerText = s;
s = s
    .Replace( "&" , "&amp;"  )
    .Replace( "<" , "&lt;"   )
    .Replace( ">" , "&gt;"   )
    .Replace( "\"", "&quot;" )
    .Replace( "'" , "&apos;" )
    .Replace( "\r", "&#xD;"  )
    .Replace( "\n", "&#xA;"  )
;
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" );
Run Code Online (Sandbox Code Playgroud)

这个程序的输出是:

<?xml version="1.0"?>
<root>
  <normal attribute="return[&#xD;] newline[&#xA;] special[&amp;&lt;&gt;&quot;']">return[
] newline[
] special[&amp;&lt;&gt;"']</normal>
  <encoded attribute="return[&#xD;] newline[&#xA;] special[&amp;&lt;&gt;&quot;']">return[
] newline[
] special[&amp;&lt;&gt;"']</encoded>
</root>
Run Code Online (Sandbox Code Playgroud)

提前致谢。克里斯。

cod*_*ife 1

使用怎么样HttpUtility.HtmlEncode()
http://msdn.microsoft.com/en-us/library/73z22y6h.aspx

好吧,抱歉,这里的线索有误。HttpUtility.HtmlEncode()不会处理您面临的换行问题。

此博客链接将为您提供帮助,尽管
http://weblogs.asp.net/mschwarz/archive/2004/02/16/73675.aspx

基本上,换行处理是由xml:space="preserve"属性控制的。

示例工作代码:

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();
Run Code Online (Sandbox Code Playgroud)

输出将显示:

<ROOT xml:space="preserve">1234
5678<CHILD>1234
5678</CHILD></ROOT>
Run Code Online (Sandbox Code Playgroud)