www
www

Reputation: 31

Get the string values of attributes in XPATH

How can I get the values of an attribute node with XPath? Example XML file:

<model:testFile name="$test1$">
  <model:task exec="/" />
</model:testFile>
<model:testFile name="$test2$">
  <model:task exec="/" />
</model:testFile>

I need to get the string values for the attribute name.

If I use: string(//model:testFile/@name), I get $test1$ as an output.

This is how I would like the output for the example above to look like:

$test1$
$test2$

Upvotes: 2

Views: 554

Answers (2)

Michael Kay
Michael Kay

Reputation: 163262

The string() function returns a single string. In XPath 1.0, if you apply it to a sequence of >1 node, it gives you the string value of the first node. In 2.0+ it gives you an error.

In XPath 1.0 there is no such data type as "a sequence of strings", so you cannot return a sequence of strings from your expression however hard you try. What you can do is return a sequence of nodes, and have the host application extract the string values of the nodes.

In XPath 2.0 you can return a sequence of strings: use //model:testFile/@name/string(). Or you can join the strings into a single string with a newline separator using string-join(//model:testFile/@name, '&#xa;'). (I've used XML escaping for the newline here; if the XPath is hosted in a language that represents newline as \n, then use that instead.)

Please always say which XPath version you are using - it makes it much easier to answer questions helpfully.

Upvotes: 2

Jack Fleeting
Jack Fleeting

Reputation: 24930

Not sure which xpath processor you are using, but try this:

string-join(//model:testFile/@name,' ')

Upvotes: 0

Related Questions