简体   繁体   中英

C# - Select XML Descendants with 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?

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">ת&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");

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM