C# - 使用 Linq 选择 XML 后代
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1439346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - Select XML Descendants with Linq
提问by Yan
I have the following XML structure:
我有以下 XML 结构:
<row>
<field name="Id">1</field>
<field name="AreaId">1</field>
<field name="Name">?"?</field>
</row>
<row>
<field name="Id">2</field>
<field name="AreaId">4</field>
<field name="Name">???????</field>
</row>
I want to iterate over the name
nodes with Linq.
I tried this:
我想name
用 Linq遍历节点。我试过这个:
var items = (from i in doc.Descendants("row")
select new
{
Text = i.Value
}).ToList();
But it didn't work the way I need it to. Any suggestions?
但它没有按照我需要的方式工作。有什么建议?
采纳答案by Mehrdad Afshari
var items = doc.Descendants("field")
.Where(node => (string)node.Attribute("name") == "Name")
.Select(node => node.Value.ToString())
.ToList();
回答by Ray Booysen
First of all, make sure your XML has a single root node:
首先,确保您的 XML 有一个根节点:
<rows>
<row>
<field name="Id">1</field>
<field name="AreaId">1</field>
<field name="Name">?"?</field>
</row>
<row>
<field name="Id">2</field>
<field name="AreaId">4</field>
<field name="Name">???????</field>
</row>
</rows>
After that you can use the following code to load the xml:
之后,您可以使用以下代码加载 xml:
string xml = //Get your XML here
XElement xElement = XElement.Parse(xml);
//This now holds the set of all elements named field
var items =
xElement
.Descendants("field")
.Where(n => (string)n.Attribute("name") == "Name");
回答by Perry Tribolet
I think Linq to Sql is the most direct approach:
我认为 Linq to Sql 是最直接的方法:
var items = (from c in doc.Descendants("field")
where c.Attribute("name").Value == "Name"
select c.Value
).ToList();