加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用XmlDocument转义换行符

发布时间:2020-12-15 21:16:10 所属栏目:百科 来源:网络整理
导读:我的应用程序使用XmlDocument生成 XML.某些数据包含换行符和回车符. 将文本分配给XmlElement时,如下所示: e.InnerText = "HellonThere"; 生成的XML如下所示: eHelloThere/e XML的接收者(我无法控制)将新行视为空格,并将上述文本视为: "Hello There" 为了
我的应用程序使用XmlDocument生成 XML.某些数据包含换行符和回车符.

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

e.InnerText = "HellonThere";

生成的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:TempXmlNewLineHandling.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 = "1234rn5678";

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 = "1234rn5678";
doc.DocumentElement.AppendChild(child);

Console.WriteLine(doc.InnerXml);
Console.ReadLine();

输出将显示为:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读