Tuesday, July 28, 2009

How to remove or ignore Document Type Definition (DTD) declarations/ Doctype from XML Files using C#

If you want to read an XML file and XML file itself has reference to DTD file or schema file. You may get error if you do not referent them correctly. On the other hand, sometime it is not necessary to have it for reading purpose. You might want to remove the Doctype declarations. The following code should help you to remove Doctype or ignore Doctype
private void Remove_Doctype_From_XML(String strXmlFile)
{
try
{
XmlDocument XDoc = new XmlDocument();
XDoc.Load(strXmlFile);
XmlDocumentType XDType = XDoc.DocumentType;
XDoc.RemoveChild(XDType);

//... Proceed reading

//...Or Saving to file
XDoc.Save(strXmlFile+ ".xml");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}