我有一些 XML 作为字符串从 Web 服务返回(不幸的是我无法控制它是如何返回给我的。它通常是有效的 XML,但有时我会收到一些稍微无效的,这会导致这个问题)。
字符串基本上是这样写的:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<STATUS _Description="...will contact you with a ("Quote") when ..." />
当我尝试这样做时:XDocument.Parse(xmlString);
它抛出以下错误:
'Quote' is an unexpected token. Expecting white space. Line 15, position 113.
这是意料之中的事,但我想不出正确的字符串操作来修复它。我尝试了很多事情,包括:
static string RemoveInvalidXmlChars(string xmlString)
{
var validXmlChars = xmlString.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();
return new string(validXmlChars);
}
和:xmlString = xmlString.Replace("\"", """);(以及许多其他组合,例如 (Replace(@"""", "")等)
抛出错误:
"'&' is an unexpected token. The expected token is '\"' or '''. Line 1, position 15."}
我也试过 xmlString = SecurityElement.Escape(xmlString); (它抛出与上面相同的错误)。我也尝试过使用 XmlWriter/Reader 修改字符串,但是当读取器到达有问题的元素时会抛出错误。
我的下一个猜测是使用正则表达式将嵌套引号转换为单引号,但 RegEx 对我来说有点陌生。我该如何解决这个问题,以便我可以使用 XDocument.Parse 对其进行解析?
请您参考如下方法:
您作为 XML 发布的字符串是在调试时检查 Visual Studio 中的一些变量,对吧?
好吧,Visual Studio 会自动转义双引号,因此您只需将该值轻松复制到 C# 代码中即可。事实上,您的 XML 并不包含所有这些\"组,而只是包含 "。所以不是\"它包含 "。您的实际问题在这里:
"Thank you for your order! The order is currently being reviewed by a moderator. A moderator will contact you with a ("Quote") when the review is complete."
问题出在另一个双引号字符串中的“Quote”双引号字符串。因此,报价相关的错误。字符串在 Quote 开始的地方结束。它似乎是一个意想不到的标记。您的 XML 提供程序实际上没有转义 Quote 单词周围的双引号。
