如何替换所有 &、<、>在解析为 XElement 之前在字符串中? [英] How to replace all &, <, > in string before parsing to XElement?

查看:34
本文介绍了如何替换所有 &、<、>在解析为 XElement 之前在字符串中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串

"<root><text>My test is > & < </text></root>"

实际上这是正确的 xml,除了 &、<、> 符号.

Actually this is correct xml, except &, <, > symbols.

我需要把它转换成我的测试是&gt;&amp;&lt;</text></root> 在我用 XElement.Parse(str); 转换它之前;

I need to convert it to <root><text>My test is &gt; &amp; &lt; </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.

这篇关于如何替换所有 &amp;、&lt;、&gt;在解析为 XElement 之前在字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆