Alex Rivera | Logout

How to ignore comments when reading a XML file into a XmlDocument?

Asked 2010-05-20T16:10:41.797
27

I am trying to read a XML document with C#, I am doing it this way:

XmlDocument myData = new XmlDocument();
myData.Load("datafile.xml");

anyway, I sometimes get comments when reading XmlNode.ChildNodes.

For the benefit of who's experiencing the same requirement, here's how I did it at the end:

/** Validate a file, return a XmlDocument, exclude comments */
private XmlDocument LoadAndValidate( String fileName )
{
    // Create XML reader settings
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.IgnoreComments = true;                         // Exclude comments
    settings.ProhibitDtd = false;                           
    settings.ValidationType = ValidationType.DTD;           // Validation

    // Create reader based on settings
    XmlReader reader = XmlReader.Create(fileName, settings);

    try {
        // Will throw exception if document is invalid
        XmlDocument document = new XmlDocument();
        document.Load(reader);
        return document;
    } catch (XmlSchemaException) {
        return null;
    }
}

Thank you
Tommaso

Edit
Report

1 Answer

4

use XmlReaderSettings

XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
XmlReader reader = XmlReader.Create(sourceFilePath, readerSettings);
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load(reader);
answered 2010-05-20T16:18:17.583

Your Answer