仅转义 XML 中 Node 的内容
我有一部分代码如下所示。
//Reading from a file and assign to the variable named "s"
string s = "<item><name> Foo </name></item>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(s);
但是,如果内容包含“<”、“>”等字符,它就会停止工作。
string s = "<item><name> Foo > Bar </name></item>";
我知道,我必须在加载之前转义这些字符,但是,如果我确实喜欢
doc.LoadXml(System.Security.SecurityElement.Escape(s));
,标签(<,>)也会被转义,结果会发生错误。
我该如何解决这个问题?
I have a part of code mentioned like below.
//Reading from a file and assign to the variable named "s"
string s = "<item><name> Foo </name></item>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(s);
But, it stops working if the contents has characters something like "<", ">"..etc.
string s = "<item><name> Foo > Bar </name></item>";
I know, I have to escape those characters before loading but, if I do like
doc.LoadXml(System.Security.SecurityElement.Escape(s));
, the tags (< , >) are also escaped and as a result, the error occurs.
How can I solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个棘手的解决方案:
a tricky solution:
假设您的内容绝不会包含字符“]]>”,您可以使用CDATA。
否则,您需要对特殊字符进行 html 编码,并在使用/显示它们之前对其进行解码(除非在浏览器中)。
Assuming your content will never contain the characters "]]>", you can use CDATA.
Otherwise, you'll need to html encode your special characters, and decode them before you use/display them (unless it's in a browser).
将字符串的内容分配给节点的
InnerXml
属性。看看 - 在 C# 中转义 XML 字符串的不同方法
Assign the content of string to the
InnerXml
property of node.Take a look at - Different ways how to escape an XML string in C#
您生成的字符串似乎是字符串,而不是有效的 XML。您可以获取生成为有效 XML 的字符串,或者如果您知道字符串始终是名称,则不要包含 XML
和;
数据中的标签。然后当您创建
XMLDocument
时。在重新保存结果之前执行CreateElement
并分配您的字符串。It looks like the strings that you have generated are strings, and not valid XML. You can either get the strings generated as valid XML OR if you know that the strings are always going to be the name, then don't include the XML
<item>
and<name>
tags in the data.Then when you create the
XMLDocument
. do aCreateElement
and assign your string before resaving the results.