【问题标题】:Check if specific xml node exists [duplicate]检查特定的xml节点是否存在[重复]
【发布时间】:2017-09-17 08:15:33
【问题描述】:

我正在尝试检查我的 xml 文件中是否存在节点“DEF”

我的 xml 文件如下所示:

<Struct>
   <A>
      <ABC>
      </ABC>
      <DEF>
      </DEF>
   </A>
   <B>
      <GHI>
      </GHI>
   </B>
</Struct>

我的代码如下所示:

XmlDocument stru = new XmlDocument();
stru.Load(path + "Structure.xml");
if (stru.ChildNodes[0].HasChildNodes)
{
    for (int i = 0; i < stru.ChildNodes[0].ChildNodes.Count; i++)
    {
        if (stru.ChildNodes[0].ChildNodes[i].Attributes["DEF"] != null)
        {
            enabled = true;
            break;
        }
        else
        {
            MessageBox.Show("no");
        }

    }
}
else { MessageBox.Show("Error!"); }

它会立即显示带有“错误!”的消息框在里面

【问题讨论】:

  • 你调试了吗?这也不是一个有效的 xml 结构。 123 不是有效的 xml 节点
  • 哦,它们有自己的名字,但我想简化它们,给我一点时间来编辑它。
  • 节点“2”到底是什么意思?
  • Opps,已编辑

标签: c# xml


【解决方案1】:

使用 linq to xml 与 Descendants:

按文档顺序返回此文档或元素的后代元素的过滤集合。集合中仅包含具有匹配 XName 的元素。(继承自 XContainer。)

var abcs = XDocument.Load("data.xml").Descendants("ABC");
if(abcs.Any())
{
    // There is at least one element of "ABC"
}

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多