Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath and XPathSelectElement

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.

like image 253
gsharp Avatar asked Jun 09 '11 08:06

gsharp


People also ask

What is Xpathselectelement?

XPathSelectElements(XNode, String) Selects a collection of elements using an XPath expression. XPathSelectElements(XNode, String, IXmlNamespaceResolver) Selects a collection of elements using an XPath expression, resolving namespace prefixes using the specified IXmlNamespaceResolver.

Is XPath the same as XML?

XPath grew out of efforts to share a common syntax between XSL Transformations (XSLT) and XPointer. It allows for the search and retrieval of information within an XML document structure. XPath is not an XML syntax: rather, it uses a syntax that relates to the logical structure of an XML document.

What is XPath in XML example?

XPath uses path expressions to select nodes or node-sets in an XML document. These path expressions look very much like the expressions you see when you work with a traditional computer file system. XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and C++, and lots of other languages.

What is XPath in API?

The XPath language provides a simple, concise syntax for selecting nodes from an XML document. XPath also provides rules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value.


2 Answers

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"
like image 166
dtb Avatar answered Sep 18 '22 14:09

dtb


var dbName = doc.XPathSelectElement("root/databases/db2").Attribute("name");
like image 23
Alex Aza Avatar answered Sep 18 '22 14:09

Alex Aza