c# - C#XML根据属性获取节点

标签 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;


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

最佳答案

好吧,对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")


代替。

关于c# - C#XML根据属性获取节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17022622/

相关文章:

c# - Linq 样式 "For Each"

c# - SQLite不保存记录

c# - Resharper - "Widen Scope"功能

Android Camera2 旋转错误

xml - XSLT 更新仅给定属性的新值和 XPath 的属性

c# - 使用 LINQ 和委托(delegate)执行递归函数

c# - 从文件中检索数据并存储在变量c#中

c# - C++ 调用托管 COM 对象找不到相关程序集

java - 如何使用单个 jaxb 实例生成 xml

c# - 搜索列表比使用 foreach 更好的方法