2011-03-01 116 views
4

我的應用程序使用XmlDocument生成XML。一些數據包含換行符和回車符。使用XmlDocument轉義換行符

當文本被分配給的XmlElement這樣的:

e.InnerText = "Hello\nThere"; 

生成的XML看起來像這樣:

<e>Hello 
There</e> 

的XML(我無法控制的)的接收器對待新行作爲空格,並將上面的文字看作:

"Hello There" 

對於接收方來說ret泉新行它需要編碼爲:如果數據被施加到一個XmlAttribute

<e>Hello&#xA;There</e> 

,新的行被正確編碼。

我試過應用文本到XmlElement使用InnerText和InnerXml但輸出是相同的兩個。

有沒有辦法讓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> 

預先感謝。 Chris。

+0

你想要什麼不明確。請顯示你想要的,以及你得到的東西 – TFD

+0

看看前4個代碼行:我從什麼開始,我得到什麼,接收者看到什麼,我想要什麼。屬性按我想要的方式對換行符進行編碼,而元素則不會。 –

回答

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(); 

輸出將閱讀:

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

我測試過這個,我的接收器無法識別或處理xml:space屬性。新行必須編碼爲 ,否則它們會轉換爲空白。 –

0

編碼可能是使用methods described here你最好的選擇。或者,您可以考慮使用CData section來代替您的內容。

+0

在我上面的示例代碼中,有一個簡單的編碼器。問題是讓XmlElement保留編碼的字符。它不斷將它們轉換回換行符和回車符。 –

0

在.net 2中。0使用XmlDocument PreserveWhitespace開關

XmlDocument d = new XmlDocument(); 
d.PreserveWhitespace = true; 
+1

當我嘗試這個時,它對新行字符的編碼沒有影響。 –