【发布时间】:2011-03-01 21:33:56
【问题描述】:
我的应用程序使用 XmlDocument 生成 XML。部分数据包含换行符和回车符。
当像这样将文本分配给 XmlElement 时:
e.InnerText = "Hello\nThere";
生成的 XML 如下所示:
<e>Hello
There</e>
XML 的接收者(我无法控制)将换行符视为空白,并将上述文本视为:
"Hello There"
为了让接收者保留换行符,它需要编码为:
<e>Hello
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( "&" , "&" )
.Replace( "<" , "<" )
.Replace( ">" , ">" )
.Replace( "\"", """ )
.Replace( "'" , "'" )
.Replace( "\r", "
" )
.Replace( "\n", "
" )
;
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[
] newline[
] special[&<>"']">return[
] newline[
] special[&<>"']</normal>
<encoded attribute="return[
] newline[
] special[&<>"']">return[
] newline[
] special[&<>"']</encoded>
</root>
提前致谢。 克里斯。
【问题讨论】:
-
你想要什么不清楚。请展示你想要什么,你得到什么
-
查看前 4 行代码:我从什么开始,我得到什么,接收者看到什么,我想要什么。属性以我想要的方式编码换行符,元素不会。
标签: c# xml .net-2.0 xmldocument