Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Select XML Descendants with Linq

Tags:

c#

xml

linq

I have the following XML structure:

<row>
  <field name="Id">1</field>
  <field name="AreaId">1</field>
  <field name="Name">ת&quot;א</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?

like image 989
Yan Avatar asked Sep 17 '09 14:09

Yan


3 Answers

var items = doc.Descendants("field")
               .Where(node => (string)node.Attribute("name") == "Name")
               .Select(node => node.Value.ToString())
               .ToList();
like image 173
mmx Avatar answered Nov 15 '22 23:11

mmx


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">ת&quot;א</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");
like image 25
Ray Booysen Avatar answered Nov 15 '22 22:11

Ray Booysen


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();
like image 40
Perry Tribolet Avatar answered Nov 15 '22 22:11

Perry Tribolet