XMLDocument读取XML文档注释问题

4

我正在使用XmlDocument解析xml文件,但是它似乎总是将xml注释读取为xml节点:

我的C#代码

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

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

}

Xml文件

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

不应该让.NET跳过XML注释吗?

1
一个小细节:XmlDocument 与 C#无关,它是 .NET 的一部分,而不是 C#的一部分。 - John Saunders
3个回答

7
不,但node.NodeType应该是XmlNodeType.Comment
如果它不读取注释,那么您也不能访问它们,但您可以执行以下操作来获取所有“真实节点”:
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
}

或者不使用LINQ/XDocument:

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

foreach (XmlNode node in xml.FirstChild.ChildNodes)
{
     if(node.NodeType != XmlNodeType.Comment)
     {
         //your code
     }
}

1
我认为应该是 " where n.NodeType != XmlNodeType.Comment ",对吗? - icn

1

试试这个

        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.
            }
       }

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接