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