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.