如何使用LINQ识别特定节点是否存在?

时间:2010-08-30 03:42:49

标签: xml linq

示例XML:

<MenuDataResult>
  <Items>
    <Item>
      <ItemType>Submenu</ItemType>
      <ItemTitle>Level22</ItemTitle>
      <Menu>
        <MenuSelected>false</MenuSelected>
        <ChildMenuSelected>false</ChildMenuSelected>
      </Menu>
    </Item>
    <Item>
      <ItemType>Submenu</ItemType>
      <ItemTitle>Level21</ItemTitle>
      <Menu>
        <MenuSelected>false</MenuSelected>
        <!--if ChildMenuSelected = true -->
        <ChildMenuSelected>true</ChildMenuSelected>
        <Item>
          <ItemType>Submenu</ItemType>
          <ItemSubType>0</ItemSubType>
          <Menu>
            <!--if MenuSelected = true -->
            <MenuSelected>true</MenuSelected>
            <ChildMenuSelected>false</ChildMenuSelected>
            <!-- whether this below item exists or not -->
            <Item>
                 <ItemType>Submenu</ItemType>
                 <Menu>
                    <MenuSelected>false</MenuSelected>
                    <ChildMenuSelected>false</ChildMenuSelected>
                </Menu>
             </Item>
          </Menu>
        </Item>
        <Item>
          <ItemType>Submenu</ItemType>
          <ItemTitle>Level32</ItemTitle>
          <Menu>
            <MenuSelected>false</MenuSelected>
            <ChildMenuSelected>false</ChildMenuSelected>
          </Menu>
        </Item>
        <Item>
          <ItemType>Library</ItemType>
          <ItemTitle>about_banner</ItemTitle>
        </Item>
        <Item>
          <ItemType>ExternalLink</ItemType>
          <ItemTitle>Google</ItemTitle>
        </Item>
      </Menu>
    </Item>
  </Items>
</MenuDataResult>

1 个答案:

答案 0 :(得分:0)

选择所有节点,然后比较标记名称...

var xmlString = @"<?xml version=""1.0""?><Root><NodeA></NodeA></Root>";

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
var nodes = xmlDoc.SelectNodes("//*");

var hasNodeA = nodes.Cast<XmlNode>().Any(n => n.Name == "NodeA"); // true
var hasNodeB = nodes.Cast<XmlNode>().Any(n => n.Name == "NodeB"); // false