tags:

views:

630

answers:

3

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?

+1  A: 

Hi avi

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
+4  A: 
var items = doc.Descendants("field")
               .Where(node => (string)node.Attribute("name") == "Name")
               .Select(node => node.Value.ToString())
               .ToList();
Mehrdad Afshari
+1  A: 

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