LINQ2XML Example

This is one of the code sample which I worked over a forum.

From the xml file given below, we need to select the nodes with category attribute of value pending.

 

<root>
  <fault category=”pending”>
    <text>Pending Fault found on</text>
  </fault>
  <fault category=”repaired”>
    <text>Repaired Fault on</text>
  </fault>
  <genere>
    <text1>Aircraft</text1>
    <text2>Component</text2>
    <text3>Subsystem</text3>
  </genere>
</root>

 

Following the LINQ2XML Code to attain the same:

 

XElement xElement = XElement.Load(@”c:\temp\xml.txt”);
            var list = (from e in xElement.Elements(“fault”) where e.Attribute(“category”).Value == “pending”
                 select e).ToList();

            foreach (XElement xe in list)
                Console.WriteLine(xe.Value);

            Console.ReadKey(false);

Leave a Reply

Your email address will not be published. Required fields are marked *