[英]Set XML as value of an XML node attribute
我正在嘗試在C#
創建一個XML
文檔,在其中一個屬性中將另一個XML作為值:
XmlDocument doc = new XmlDocument();
XmlElement nodElement = doc.CreateElement(string.Empty, "node", string.Empty);
nodElement.SetAttribute("text", MyXMLToInsert);
doc.AppendChild(nodElement);
MyXMLToInsert
會是這樣的:
<xml xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
.
.
如何防止第二個XML的特殊字符與主要字符沖突? 謝謝。
如果必須在XML文檔中保存XML文本,則必須使用XML編碼。 如果不轉義特殊字符,則要插入的XML將成為原始XML DOM的一部分,而不是節點的值。
轉義XML意味着基本上用新值替換5個字符。
這些替代品是:
< -> <
> -> >
" -> "
' -> '
& -> &
以下是使用C#編碼XML的4種方法:
string.Replace() 5 times
這很丑,但它確實有效。 請注意,Replace(“&”,“&”)必須是第一個替換,因此我們不會替換其他已經轉義的&。
string xml = "<node>it's my \"node\" & i like it<node>";
encodedXml = xml.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'");
// RESULT: <node>it's my "node" & i like it<node>
System.Web.HttpUtility.HtmlEncode()
用於編碼HTML,但HTML是XML的一種形式,因此我們也可以使用它。 主要用於ASP.NET應用程序。 請注意,HtmlEncode不編碼撇號(')。
string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = HttpUtility.HtmlEncode(xml);
// RESULT: <node>it's my "node" & i like it<node>
System.Security.SecurityElement.Escape()
在Windows窗體或控制台應用程序中,我使用此方法。 如果沒有別的東西它可以節省我,包括我的項目中的System.Web參考,它編碼所有5個字符。
string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = System.Security.SecurityElement.Escape(xml);
// RESULT: <node>it's my "node" & i like it<node>
System.Xml.XmlTextWriter
使用XmlTextWriter,您不必擔心轉義任何內容,因為它會在需要的地方轉義字符。 例如,在屬性中它不會轉義撇號,而在節點值中它不會轉義撇號和qoutes。
string xml = "<node>it's my \"node\" & i like it<node>";
using (XmlTextWriter xtw = new XmlTextWriter(@"c:\xmlTest.xml", Encoding.Unicode))
{
xtw.WriteStartElement("xmlEncodeTest");
xtw.WriteAttributeString("testAttribute", xml);
xtw.WriteString(xml);
xtw.WriteEndElement();
}
// RESULT:
/*
<xmlEncodeTest testAttribute="<node>it's my "node" & i like it<node>">
<node>it's my "node" & i like it<node>
</xmlEncodeTest>
*/
調用SetAttribute方法將負責轉義數據。
假設您從位於應用程序根目錄中的文件“Text.txt”中讀取MyXMLToInsert的內容。
var doc = new XmlDocument();
var nodElement = doc.CreateElement(string.Empty, "node", string.Empty);
nodElement.SetAttribute("text", File.ReadAllText("text.txt"));
doc.AppendChild(nodElement);
屬性的值將自動轉義(使用XML轉義碼)到...
<node text="<xml xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"
xmlns="http://www.w3.org/TR/REC-html40">

<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.