XPath and XPathSelectElement

gsharp picture gsharp · Jun 9, 2011 · Viewed 41.1k times · Source

I have the following xml

<root>
   <databases>
      <db1 name="Name1" />
      <db2 name="Name2" server="myserver" />
      <db3 name="Name3" />
   </databases>
<root>

I've tried everything to read the name of the db2 (="Name2") with all possible combinations of XPath queries, but never get the expected result.

My Code so far:

var query = "root/databases/db2.. "; // here I've tried everything 
var doc = XDocument.Load("myconfig.xml");
var dbName =  doc.XPathSelectElement(query);

What's the correct query to get my "Name2" (the value of the Attribute) ?

Thanks for your help.

Answer

dtb picture dtb · Jun 9, 2011

The XPathSelectElement method can only be used to select elements, not attributes.

For attributes, you need to use the more general XPathEvaluate method:

var result = ((IEnumerable<object>)doc.XPathEvaluate("root/databases/db2/@name"))
                                      .OfType<XAttribute>()
                                      .Single()
                                      .Value;

// result == "Name2"