Parsing a xml string & retrieving its attribute Value using Linq to XML C#

c#, c#-4.0, linq, linq-to-xml, xml

Solution

Following LINQ to XML query will return sequence of anonymous objects with id, lang, and working status of `pub` elements:

var xdoc = XDocument.Parse(myXmlData);
var query = 
  from p in xdoc.Root.Elements("pub")
  let ws = p.Elements("configitem")
            .FirstOrDefault(c => (string)c.Attribute("name") == "working_status")
  select new {
      Id = (string)p.Attribute("id"),
      Lang = (string)p.Attribute("lang"),
      WorkingStatus = (ws == null) ? null : (string)ws.Attribute("value")
  };

For your sample xml it returns two objects with following data:

{
   Id = "pubId1",
   Lang = "en-US",
   WorkingStatus = "unlocked"
},
{
   Id = "Pub2",
   Lang = "es-XM",
   WorkingStatus = null
}

Problem

I am quite new to Linq to XML & trying to Parse a xml string & retrieve its attribute Value using Linq to XML in C#. My XML string looks like : ``` <configuration xmlns:lui="http://www.xyz.com/UITags"> <pub id="pubId1" lang="en-US"> <configitem name="visible" value="visible"/> <configitem name="working_status" value="unlocked"/> <configitem name="prepared" value="prepared"/> </pub> ..... ..... <pub id="Pub2" lang="es-XM">...</pub> .... .... </configuration> ``` I want to fetch the value of 'id' & 'lang' from pub node & value of attribute named 'working_status' from configitem Node. Now as I am getting the above xml as a string parameter (i.e. myXmlData), by doing ``` XmlDocument doc = new XmlDocument(); doc.LoadXml(myXmlData); XmlNodeList publicationsNodeList = doc.SelectNodes("//configuration/pub"); ``` ... ... Then I have to loop through using foreach, which I want to avoid as much as possible. Can anyone help me how to achieve this using Linq to XML in C#, rather then conventional way.

Original source