解析包含非法字符的 XML

mit*_*llt 4 c# xml

我从服务器收到的消息包含标签,标签中包含我需要的数据。

我尝试将有效负载解析为XML,但生成了非法字符异常。

我也使用httpUtilitySecurity 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>
Run Code Online (Sandbox Code Playgroud)

Ulu*_*rov 6

如果您只有&无效字符,那么您可以使用正则表达式将其替换为&amp;. 我们使用正则表达式来防止替换现有的&amp;&quot;&#111;等符号。

正则表达式可以如下:

&(?!(?:lt|gt|amp|apos|quot|#\d+|#x[a-f\d]+);)
Run Code Online (Sandbox Code Playgroud)

正则表达式可视化

示例代码:

string content = @"<item><code>1234 &amp; 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]+);)", "&amp;", RegexOptions.IgnoreCase);
XElement xItem = XElement.Parse(content);
Run Code Online (Sandbox Code Playgroud)