[英]C# XML get nodes based on attribute
I have the following xml: 我有以下xml:
<root ...>
<Tables>
<Table content="..">
</Table>
<Table content="interesting">
<Item ...></Item>
<Item ...></Item>
<Item ...></Item>
</Table>
...etc...
</Tables>
</root>
I'm using the following code to get the items from the 'interesting' node: 我正在使用以下代码从“有趣的”节点获取项目:
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;
Is there a simpler, cleaner way to achieve this? 有没有更简单,更清洁的方法来实现这一目标?
Well there's no point in using a query expression for items
, and you can wrap the whole thing up very easily in a single statement. 好吧,对
items
使用查询表达式毫无意义,并且您可以非常轻松地将整个内容包装在单个语句中。 I wouldn't even bother with a query expression for that: 我什至不会为查询表达式而烦恼:
var items = XElement.Parse(resp)
.Elements("Tables")
.Elements("Table")
.Where(n => n.Attribute("content").Value == "interesting")
.Elements();
Note that this (and your current query) will throw an exception for any Table
element without a content
attribute. 请注意,此操作(和您当前的查询)将为任何没有
content
属性的Table
元素引发异常。 If you'd rather just skip it, you can use: 如果您只想跳过它,则可以使用:
.Where(n => (string) n.Attribute("content") == "interesting")
instead. 代替。
您可以使用XPath(扩展名在System.Xml.XPath命名空间中)在一行中选择所有项:
var items = xel.XPathSelectElements("//Table[@content='interesting']/Item");
If you don't need nodes
outside of your query for items
, you can just do this: 如果您不需要查询之外的
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;
using xml document 使用xml文件
XmlDocument xdoc = new XmlDocument(); XmlDocument xdoc =新的XmlDocument();
var item= xdoc.GetElementsByTagName("Table[@content='interesting']/Item"); var item = xdoc.GetElementsByTagName(“ Table [@ content ='interesting'] / Item”);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.