X
    Categories: .NET

LINQ to XML instead of XPath

Working on a new project, I needed to read some elements from an XML file. As a matter of habit, I used XPath, but later I figured this was a good opportunity to try it out using LINQ. So here goes.

The XML source is a file, stored as Resources.xml with the following contents.


<?xml version="1.0" encoding="utf-8" ?>
<resources>
<culture code="en-US" >
<resource key="MetaData.Description" value="&quot;Realtime data on ... !&quot;" />
<resource key="MetaData.Keywords" value="&quot;images, keyword1, keyword2, keyword3&quot;" />
<resource key="Homepage.Title" value="just a random title" />
</culture>
<culture code="nl-NL" >
<resource key="MetaData.Description" value="&quot;Realtime beelden ...&quot;" />
<resource key="MetaData.Keywords" value="&quot;beelden, plaatjes, etc.&quot;" />
<resource key="Homepage.Title" value="Een willekeurige titel" />
/culture>
<culture code="fr-FR" >
...
</culture>
</resources>

The relevant data is in the value-attribute. The input parameters is culture of type CultureInfo and resourceKey of type string. resourceFile holds the path to the XML file.

The XPath version of getting to that data is this:


XmlDocument resourceXml = new XmlDocument();
resourceXml.Load(resourceFile);
string xpathQuery = string.Format("//culture[@code='{0}']/resource[@key='{1}']", culture.Name, resourceKey);
XmlNode resourceElement = resourceXml.SelectSingleNode(xpathQuery);
if (resourceElement != null) resourceValue = resourceElement.Attributes["value"].InnerText;

Using LINQ to XML we can use the following snippet:


XDocument xdoc = XDocument.Load(resourceFile);
var q = from c in xdoc.Descendants("culture")
where c.Attribute("code").Value == culture.Name
from r in c.Descendants("resource")
where r.Attribute("key").Value == resourceKey
select r.Attribute("value").Value;
if (q.Count<string>() == 1) resourceValue = q.First<string>();

Either version works fine. The only issue is that LINQ is supposed to help the developer by IntelliSense and strong typing. Unfortunately, that doesn’t happen here, at least not with the elements in the XML file.

 

 

 

Related Post
Leave a Comment