I have the following XML structure:
<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:
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?
var items = doc.Descendants("field")
.Where(node => (string)node.Attribute("name") == "Name")
.Select(node => node.Value.ToString())
.ToList();
First of all, make sure your XML has a single root node:
<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:
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");
I think Linq to Sql is the most direct approach:
var items = (from c in doc.Descendants("field")
where c.Attribute("name").Value == "Name"
select c.Value
).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With