繁体   English   中英

XmlDocument读取XML文档注释问题

[英]XmlDocument reading XML Document comment Issue

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

没有,但node.NodeType通过schould 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
     }
}

试试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM