开发者

How can I use LINQ to indentify if a particular node exists?

Sample 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&开发者_开发问答gt;
                </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>


Select all nodes, and then compare the tag name...

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜