微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 使用XmlDocument转义换行符

我的应用程序使用XmlDocument生成 XML.某些数据包含换行符和回车符.

将文本分配给XmlElement时,如下所示:

e.InnerText = "Hello\nThere";

生成的XML如下所示:

<e>Hello
There</e>

XML的接收者(我无法控制)将新行视为空格,并将上述文本视为:

"Hello There"

为了使接收器保留新线路,它需要编码为:

<e>Hello&#xA;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( "&","&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" );

该程序的输出是:

<?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>

提前致谢.
克里斯.

解决方法

如何使用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();

输出显示为:

<ROOT xml:space="preserve">1234
5678<CHILD>1234
5678</CHILD></ROOT>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐