Reputation: 42699
I'm attempting to print the names of multiple elements, but I can only convince XPath to output one.
Given this XML:
<xml>
<foob>931</foob>
<arba>478</arba>
<zfoo>892</zfoo>
</xml>
I try this and get foob
:
name(//*[contains(name(), "foo")])
I try this and get an error about an invalid expression:
//*[contains(name(), "foo")]/name()
Although this works fine:
//*[contains(name(), "foo")]/text()
I'm on the command line, and have tried both xmllint
and xpath
(from Perl's XML-XPath module) with the same results.
How can I get both foob
and zfoo
returned?
Upvotes: 2
Views: 89
Reputation: 111491
With XPath 1.0, your first XPath,
name(//*[contains(name(), "foo")])
results in just "foob"
because XPath 1.0 passes only the first member of the selected nodeset to name()
. To obtain a list of "foob"
and "zfoo"
, you would have to iterate over the selected nodeset in the language hosting the XPath call -- XSLT, Python, Java, etc.
With XPath 2.0, your second XPath,
//*[contains(name(), "foo")]/name()
would work fine to obtain a list of "foob"
and "zfoo"
directly via XPath alone.
Upvotes: 2