views:

189

answers:

1

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"&gt;
<!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"&gt;
  <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 an 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?

P.S: I forgot to mention, that the data comes from a Stream which may or may not make the string manipulation a little bit more complex

+1  A: 

I'm not sure if there's an XmlReader setting that will ignore this problem, but you could always use standard string manipulation to remove the extra doctypes.

David