繁体   English   中英

C#XML根据属性获取节点

[英]C# XML get nodes based on attribute

我有以下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;

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

好吧,对items使用查询表达式毫无意义,并且您可以非常轻松地将整个内容包装在单个语句中。 我什至不会为查询表达式而烦恼:

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

请注意,此操作(和您当前的查询)将为任何没有content属性的Table元素引发异常。 如果您只想跳过它,则可以使用:

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

代替。

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

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

如果您不需要查询之外的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;

使用xml文件
XmlDocument xdoc =新的XmlDocument();

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

暂无
暂无

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

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