martedì 7 febbraio 2012

Ignore inline DTD in XML file with LINQ to XML

If we want to read an XML file with LINQ to XML that have DTD inline instructions, normally we use this statement

    XDocument doc = XDocument.Load("myXmlFile.xml");

but... we'll receive an exception.

The Load method of the XDocument has several overloads, including one in particular that takes as a parameter an XmlReader object.
Let's see how to use it:

  XmlReaderSettings settings = new XmlReaderSettings();
  settings.DtdProcessing = DtdProcessing.Ignore;
  XmlReader reader = XmlReader.Create("myFile.xml", settings);
  XDocument doc = XDocument.Load(reader,   LoadOptions.PreserveWhitespace);

First, create a XmlReaderSettings object and set its DtdProcessing property to "Ignore". It causes the DOCTYPE element to be ignored.
Then, create a new XmlReader object using the file path name and XmlReader previously created settings.
Now we can open without previous exception out xml file, passing XmlReader object as argument of XDocument Load method.

2 commenti:

  1. What would be the reason for the original exception thrown?

    RispondiElimina
    Risposte
    1. The reason is that the direct use of XDocument.Load ("file.xml") does not recognize the xml file inline DTD statements.

      Elimina

Your message will be verified prior to publication. Thanks for your contribution.