【问题标题】:Correct ill formed XML before I deserialize it [duplicate]在我反序列化之前纠正格式错误的 XML [重复]
【发布时间】:2014-12-02 01:28:36
【问题描述】:

由于另一个产品中的 PHP 错误,我有时会收到格式错误的 XML 响应,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<customfields>
</customfields>Warning
Router: https://example.com/api/index.php?/Tickets/TicketCustomField/Get
file_put_contents(./__swift/cache/SWIFT_Loader.cache): failed to open stream: Invalid argument (C:/Kayako/support/__swift/library/Loader/class.SWIFT_Loader.php:1630)

在我反序列化之前是否存在清理该字符串的安全方法?

重复声明是正确的,但链接的重复没有给出可行的解决方案。

当前的临时解决方案,仅在起始字符串是有效的 XML 并且附加的错误不包含另一个与根标记匹配的结束标记时才有效:

RegexOptions options = RegexOptions.Singleline | RegexOptions.Compiled;
var tidyStreamContents = Regex.Match(streamContents, @"^<\?xml.*?\?>\s*?<(.*?)>.*</(\1)>", options, Regex.InfiniteMatchTimeout).ToString();

【问题讨论】:

  • 您可以在最后一个 &gt; 之后删除所有内容,这有点天真,但它可以工作。您是否考虑过联系产品的客户支持?

标签: c# xml xml-deserialization


【解决方案1】:

您可以使用CsQuery 将无效的 XML 视为 HTML,将其清理并输出为字符串以供进一步处理:

using CsQuery;

var cq = CQ.CreateFromFile("input.txt");
var sCleanXML = cq("customfields").RenderSelection;

输入(input.txt的内容):

<?xml version="1.0" encoding="UTF-8"?>
<customfields>
</customfields>Warning
Router: https://example.com/api/index.php?/Tickets/TicketCustomField/Get
file_put_contents(./__swift/cache/SWIFT_Loader.cache): failed to open stream: Invalid argument (C:/Kayako/support/__swift/library/Loader/class.SWIFT_Loader.php:1630)

输出(sCleanXML 的值):

<customfields> </customfields>

另一种方法是使用XmlReaderHtmlAgilityPack

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-15
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 2011-09-18
    相关资源
    最近更新 更多