4

I am using XmlDocument to parse xml file, but it seems that XmlDocument is always reading xml comments as a xml nodes:

My C# code

XmlDocument xml = new XmlDocument();
xml.Load(filename);

foreach (XmlNode node in xml.FirstChild.ChildNodes) {

}

Xml file

<project>
    <!-- comments-->
    <application name="app1">
        <property name="ip" value="10.18.98.100"/>
    </application>
</project>

Shouldn't .NET skip XML comments?

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
icn
  • 17,126
  • 39
  • 105
  • 141

3 Answers3

7

No, but node.NodeType schould by XmlNodeType.Comment.
If it wouldn't read the comments you also couldn't access them, but you can do something like the following to get all "real nodes":

XDocument xml = XDocument.Load(filename);
var realNodes = from n in xml.Descendants("application")
                where n.NodeType != XmlNodeType.Comment
                select n;

foreach(XNode node in realNodes)
{ 
    //your code
}

or without LINQ/XDocument:

XmlDocument xml = new XmlDocument();
xml.Load(filename);

foreach (XmlNode node in xml.FirstChild.ChildNodes)
{
     if(node.NodeType != XmlNodeType.Comment)
     {
         //your code
     }
}
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
1

Look at XmlNodeType.Comment

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
1

Try this

        XmlDocument xml = new XmlDocument();
        xml.Load(filename);

        foreach (XmlNode node in xml.FirstChild.ChildNodes) 
        {
            if(node.GetType() == XmlNodeType.Comment)
            {
               //Do nothing
            }
            else
            {
               //Your code goes here.
            }
       }
Bibhu
  • 4,053
  • 4
  • 33
  • 63