How to ignore comments when reading a XML file into a XmlDocument? [duplicate] How to ignore comments when reading a XML file into a XmlDocument? [duplicate] xml xml

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


You can use an XmlReader with XmlReaderSettings.IgnoreComments set to true:

XmlReaderSettings readerSettings = new XmlReaderSettings();readerSettings.IgnoreComments = true;using (XmlReader reader = XmlReader.Create("input.xml", readerSettings)){    XmlDocument myData = new XmlDocument();    myData.Load(reader);    // etc...}

(Found from here by searching for XmlDocument ignore comments)


foreach(XmlNode node in nodeList)  if(node.NodeType != XmlNodeType.Comment)     ...


You could simply add filter on your ChildNodes. E.g.

var children = myNode.ChildNodes.Cast<XmlNode>().Where(n => n.NodeType != XmlNodeType.Comment);

Alternatively, you could load the XmlDocument passing in an XmlReader with settings such that XmlReaderSettings.IgnoreComments is true.

using (var file = File.OpenRead("datafile.xml")){    var settings = new XmlReaderSettings() { IgnoreComments = true, IgnoreWhitespace = true };    using (var xmlReader = XmlReader.Create(file, settings))    {        var document = new XmlDocument();        document.Load(xmlReader);        // Process document nodes...    }}