【问题标题】:Loading not-so-well-formed XML into XDocument (multiple DTD)将格式不太好的 XML 加载到 XDocument(多个 DTD)中
【发布时间】:2010-05-05 19:14:29
【问题描述】:

我在处理几乎格式良好的 XHTML 文档的数据时遇到了问题,除了它在开头有多个 DTD 声明:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    ...
  </head>
  <body>
    ...
  </body>
</html>

我需要仅使用 first DTD 和 ignoring 其余声明将此数据加载到 XDocument 对象中。不可能完全忽略 DTD 处理,因为文档可能包含不寻常的字符,例如 &amp;acirc;&amp;euro; 等。

文本是从外部来源检索的,我不知道为什么会这样。

显然,我加载此文档的天真尝试失败了 System.Xml.XmlException : Cannot have multiple DTDs

        var xmlReaderSettings = new XmlReaderSettings
                                    {
                                        DtdProcessing = DtdProcessing.Parse,
                                        XmlResolver = new XmlPreloadedResolver(),
                                        ConformanceLevel = ConformanceLevel.Document,
                                    };
        using (var xmlReader = XmlReader.Create(stream, xmlReaderSettings))
        {
            return XDocument.Load(xmlReader);
        }

处理此类数据的最佳方法是什么?

P.S:我忘了说,数据来自Stream,这可能会使字符串操作更复杂,也可能不会

【问题讨论】:

    标签: .net dtd doctype linq-to-xml xml-parsing


    【解决方案1】:

    我不确定是否有 XmlReader 设置会忽略此问题,但您始终可以使用标准字符串操作来删除额外的文档类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 2010-12-02
      相关资源
      最近更新 更多