且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

逃跑的新行字符的XmlDocument

更新时间:2023-12-03 21:01:28

如何使用 HttpUtility.HtmlEncode()?code>结果
的http:// MSDN。 microsoft.com/en-us/library/73z22y6h.aspx 击>

确定,很抱歉的错误领导那里。 HttpUtility.HtmlEncode()不可以处理你所面临的新行问题。

OK, sorry about the wrong lead there. HttpUtility.HtmlEncode() will not handle the newline issue you're facing.

这个博客链接将会帮助你,尽管

http://weblogs.asp.net/mschwarz/archive/2004/02/16/73675.aspx

This blog link will help you out, though
http://weblogs.asp.net/mschwarz/archive/2004/02/16/73675.aspx

基本上,换行符处理由 XML控制:空间=保存属性

Basically, the newline handling is controlled by the xml:space="preserve" attribute.

样品工作代码:

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>