10

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?

Donut
  • 110,061
  • 20
  • 134
  • 146
Yan
  • 1,424
  • 4
  • 21
  • 44

3 Answers3

19
var items = doc.Descendants("field")
               .Where(node => (string)node.Attribute("name") == "Name")
               .Select(node => node.Value.ToString())
               .ToList();
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
11

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");
Ray Booysen
  • 28,894
  • 13
  • 84
  • 111
1

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();
Perry Tribolet
  • 2,624
  • 1
  • 21
  • 9