我正在尝试在XML中创建一个C#文档,在其中一个属性中,它将获得另一个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的特殊字符不与主要字符发生冲突?谢谢。
发布于 2015-05-09 03:41:14
调用SetAttribute方法将负责转义数据。
假设您从应用程序根目录中的“MyXMLToInsert”文件中读取了Text.txt的内容。
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">" />发布于 2015-05-09 03:41:52
如何在C#中转义XML字符串的不同方法
如果必须将XML文本保存在XML文档中,则XML编码是必要的。如果不转义特殊字符,要插入的XML将成为原始XML的一部分,而不是节点的值。
转义XML基本上意味着用新值替换5个字符。
这些替代者是:
< -> <
> -> >
" -> "
' -> '
& -> &以下是4种在C#中编码XML的方法:
string.Replace() 5 times这很难看,但很管用。请注意,替换(“&”、"&")必须是第一个替换,因此我们不会替换其他已经转义的&。
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>
*/https://stackoverflow.com/questions/30135657
复制相似问题