Loading not-so-well-formed XML into XDocument (multiple DTD)

Posted by Gart on Stack Overflow See other posts from Stack Overflow or by Gart
Published on 2010-04-21T16:07:16Z Indexed on 2010/04/21 16:13 UTC
Read the original article Hit count: 926

Filed under:
|
|
|
|

I have got a problem handling data which is almost well-formed XHTML document except for it has multiple DTD declarations in the beginning:

<!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>

I need load this data into XDocument object using only the first DTD and ignoring the rest declarations. It is not possible to completely ignore DTD processing because the document may have unusual characters like &acirc; or &euro; etc.

The text is retrieved from external source and I have no idea why it comes like this.

Obviously my naive attempt to load this document fails with 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);
        }

What would be the best way to handle this kind of data?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about Xml