Reputation: 2588
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.
Upvotes: 3
Views: 7805
Reputation: 204
var query = from x in xdoc.Descendants("pub")
select new
{
Id = (string)x.Attribute("id"),
Lang = (string)x.Attribute("lang"),
Name = x.Descendants("configitem").Select(y => y.Attribute("name").Value).FirstOrDefault(y => y == "working_status")
};
Upvotes: 1
Reputation: 236218
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
}
Upvotes: 5