Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 970
Biki Avatar asked Jan 23 '26 11:01

Biki


1 Answers

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
}
like image 170
Sergey Berezovskiy Avatar answered Jan 25 '26 00:01

Sergey Berezovskiy



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!