C#XML基于属性获取节点

时间:2013-06-10 11:16:09

标签: c# xml linq linq-to-xml

我有以下xml:

<root ...>
  <Tables>
    <Table content="..">
    </Table>
    <Table content="interesting">
      <Item ...></Item>
      <Item ...></Item>
      <Item ...></Item>
    </Table>
    ...etc...
  </Tables>
</root>

我正在使用以下代码从“有趣”节点获取项目:

XElement xel = XElement.Parse(resp);

var nodes = from n in xel.Elements("Tables").Elements("Table")
            where n.Attribute("content").Value == "interesting"
            select n;

var items = from i in nodes.Elements()
            select i;

是否有更简单,更清洁的方法来实现这一目标?

4 个答案:

答案 0 :(得分:5)

使用items的查询表达式没有意义,你可以在一个语句中轻松地完成整个过程。我甚至不打扰查询表达式:

var items = XElement.Parse(resp)
                    .Elements("Tables")
                    .Elements("Table")
                    .Where(n => n.Attribute("content").Value == "interesting")
                    .Elements();

请注意,此(以及您当前的查询)将为没有Table属性的任何content元素抛出异常。如果您只是跳过它,可以使用:

.Where(n => (string) n.Attribute("content") == "interesting")

代替。

答案 1 :(得分:2)

您可以使用XPath(扩展名在 System.Xml.XPath 命名空间中)选择一行中的所有项目:

var items = xel.XPathSelectElements("//Table[@content='interesting']/Item");

答案 2 :(得分:1)

如果您在查询nodes之外不需要items,则可以执行以下操作:

var items = from n in xel.Elements("Tables").Elements("Table")
            where n.Attribute("content").Value == "interesting"
            from i in n.Elements()
            select i;

答案 3 :(得分:1)

使用xml文件
  XmlDocument xdoc = new XmlDocument();

var item = xdoc.GetElementsByTagName(“Table [@ content ='interesting'] / Item”);

相关问题