user2847238
user2847238

Reputation: 169

Reading XML nodes with LINQ

I have a trouble reading from XML file using LINQ.

Here is my XML file

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee>
    <Name Type="First">Jack</Name>
    <Name Type="Last">Black</Name>
  </Employee>
  <Employee>
    <Name Type="First">John</Name>
    <Name Type="Last">Blue</Name>
  </Employee>
  <Employee>
    <Name Type="First">Dan</Name>
    <Name Type="Last">Red</Name>
  </Employee>
  <Employee>
    <Name Type="First">Patrick</Name>
    <Name Type="Last">Green</Name>
  </Employee>
</Employees>

The code I am using is following

    XElement doc = XElement.Load("xmldoc.xml");
    var query = from x in doc.Elements("Employee") where x.Element("Name").Attribute("Type").Value == "First" select x;
    foreach (XElement item in query)
    {
        Console.WriteLine(item.Element("Name").Value);
    }

This code returns me all first names but when i change attribute value from first to last it comes blank.

When i switch name nodes it retuns last names. For me it looks like for each employe query returns values from first name node and ignoring the second one. Could you please help me fix this?

Upvotes: 3

Views: 5454

Answers (1)

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

The problem is that the x.Element("Name") call will return the first Name element. You actually need to query all the Name elements and filter for the one with the Last attribute value.

Try this instead:

var query = from x in doc.Elements("Employee").Elements("Name")
            where x.Attribute("Type").Value == "Last"
            select x;

foreach (XElement item in query)
{
    Console.WriteLine(item.Value);
}

Upvotes: 5

Related Questions