我从服务器收到的消息包含标签,标签中是我需要的数据。
我尝试将负载解析为 XML,但生成了非法字符异常。
我还使用了 httpUtility
和 Security Utility
转义非法字符,唯一的问题是,它会转义 < >
这是解析 XML 所必需的。
我的问题是,当其中包含的数据包含非法的非 XML 字符时,我该如何解析 XML? (& -> amp;)
_
谢谢。
例子:
<item><code>1234</code><title>voi hoody & polo shirt + Mckenzie jumper</title><description>Good condition size small - medium, text me if interested</description></item>
最佳答案
如果您只有 &
作为无效字符,那么您可以使用正则表达式将其替换为 &
。我们使用正则表达式来防止替换已经存在的 &
、"
、o
等符号。
正则表达式可以如下:
&(?!(?:lt|gt|amp|apos|quot|#\d+|#x[a-f\d]+);)
示例代码:
string content = @"<item><code>1234 & test</code><title>voi hoody & polo shirt + Mckenzie jumper&other stuff</title><description>Good condition size small - medium, text me if interested</description></item>";
content = Regex.Replace(content, @"&(?!(?:lt|gt|amp|apos|quot|#\d+|#x[a-f\d]+);)", "&", RegexOptions.IgnoreCase);
XElement xItem = XElement.Parse(content);
关于c# - 解析包含非法字符的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23048158/