XmlDocument读取XML文档注释问题

本文关键字:注释 问题 文档 XML 读取 XmlDocument | 更新日期: 2023-09-27 18:00:31

我使用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注释吗?

XmlDocument读取XML文档注释问题

否,但node.NodeTypeXmlNodeType.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
     }
}

查看XmlNodeType.Comment

试试这个

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