user559142
user559142

Reputation: 12517

Using xPath in C# to get value of node attribute

If I have the following xml document:

<xml>
<data>
<dataset name="X"></dataset>
</data>
</xml>

How can I use Xpath in c# to retrieve the value of the name attribute (i.e. X)

Upvotes: 4

Views: 2101

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243559

How can I use Xpath in c# to retrieve the value of the name attribute (i.e. X)

This XPath expression:

/xml/data/dataset/@name 

selects the wanted attribute -- all atributes named name that belong to a dataset element that is a child of a data element that is a child of the top element of the XML document.

However, you want to get the value of the attribute -- not the node itself.

This XPath expression:

string(/xml/data/dataset/@name) 

when evaluated, produces the wanted string value.

In C# use the XPathNavigator.Evaluate() method to evaluate the expression above.

Upvotes: 4

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56202

Use this XPath:

xml/data/dataset/@name

Upvotes: 2

Orentet
Orentet

Reputation: 2363

use this XPath expression:

xml/data/dataset

this will retrieve the dataset node. after that you can use C# tools to retrieve the attribute name from the node.

Upvotes: 0

Related Questions