4

我正在使用 XmlDocument 来解析 xml 文件,但似乎 XmlDocument 总是将 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 注释吗?

4

3 回答 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
     }
}
于 2011-06-24T14:13:03.457 回答
1

看看XmlNodeType.Comment

于 2011-06-24T14:14:29.107 回答
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.
            }
       }
于 2011-06-24T14:20:10.960 回答