[英]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.