我从服务器收到的消息包含标签,标签中包含我需要的数据。
我尝试将有效负载解析为 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>
答案 0 :(得分:4)
如果您只有&
作为无效字符,则可以使用正则表达式将其替换为&
。我们使用正则表达式来阻止替换现有的&
,"
,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);
答案 1 :(得分:1)
这是比Regex
更通用的解决方案。首先声明一个数组,将要替换的每个无效字符与编码版本一起存储到其中:
var invalidChars = new [] { '&', other chars comes here.. };
然后读取所有xml作为整个文本:
var xmlContent = File.ReadAllText("path");
然后使用LINQ
和HttpUtility.HtmlEncode
替换无效字符:
var validContent = string.Concat(xmlContent
.Select(x =>
{
if (invalidChars.Contains(x)) return HttpUtility.HtmlEncode(x);
return x.ToString();
}));
然后使用XDocument.Parse
解析它,就是全部。
答案 2 :(得分:1)
不要将其称为&#34;包含非法字符的XML&#34;。它不是XML。您不能使用XML工具来处理不是XML的东西。
当您收到错误的XML时,最好的方法是找出生成的位置和时间,并在源头修复问题。
如果你不能这样做,你需要找到一些方法使用非XML工具(例如自定义perl脚本)来修复XML,然后再将它放在XML解析器附近。您这样做的方式取决于您需要修复的错误的性质。