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.
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.
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.
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.
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.
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"
var dbName = doc.XPathSelectElement("root/databases/db2").Attribute("name");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With