如何替换所有 &、<、>在解析为 XElement 之前在字符串中? [英] How to replace all &, <, > in string before parsing to XElement?
问题描述
我有这样的字符串
"<root><text>My test is > & < </text></root>"
实际上这是正确的 xml,除了 &、<、> 符号.
Actually this is correct xml, except &, <, > symbols.
我需要把它转换成
在我用 XElement.Parse(str); 转换它之前;
I need to convert it to <root><text>My test is > & < </text></root>
before I convert it with XElement.Parse(str);
如何进行这种转换?
推荐答案
这几乎不可能可靠地实现.您应该从源头上更正此问题.如果您控制插入My test is > & <"字符串的系统,那么您应该在插入之前转义该字符串.HttpUtility.HtmlEncode
是一种合理的方法.
This is nigh-on impossible to achieve reliably. You should correct this issue at source. If you control the system that is inserting the "My test is > & < " string, then you should escape this string before inserting it. HttpUtility.HtmlEncode
is a reasonable way of doing that.
这篇关于如何替换所有 &、<、>在解析为 XElement 之前在字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!