Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading XML nodes with LINQ

Tags:

c#

xml

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?

like image 325
user2847238 Avatar asked Feb 01 '26 21:02

user2847238


1 Answers

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);
}
like image 137
Ahmad Mageed Avatar answered Feb 04 '26 09:02

Ahmad Mageed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!