XPath for elements at multiple levels?
Asked Answered
P

3

6

I have a following XML

<?xml version="1.0" encoding="UTF-8"?>
<stationary>
    <textbook>
        <name>test</name>
    </textbook>
    <notebook>
        <books>
            <name>test</name>
        </books>
    </notebook>
</stationary>

I am trying to get all name elements irrespective of their position in stationary

I have tried using the following syntax but it didn't work:

stationary/*/name/text()
Powerboat answered 5/3, 2018 at 3:5 Comment(0)
P
3

Just use the following expression with a relative path:

//name

This seems to capture the two <name> tags you have in your XML sample:

Element='<name>test</name>'
Element='<name>test</name>'
Percyperdido answered 5/3, 2018 at 3:10 Comment(0)
R
6

Try this :

'stationary//name/text()'
Rundell answered 5/3, 2018 at 3:11 Comment(0)
P
4

Your XPath,

/stationary/*/name/text()

will only select the text nodes contained in the name element under textbook because /* selects a child element, but the other name element is a grandchild of stationary, not a child of it.

The simplest change would be to replace /*/ with // (as mentioned by @GillesQuenot, +1),

/stationary//name/text()

which will select along the descendant-or-self axis, so it'll select grandchildren, and you'll get both name elements' text() nodes.

Do note that you say you're trying to get name elements, so technically you ought to drop the text() step,

/stationary//name

which will select all name element descendants of the stationary element. Then, as a final note, this XPath (as mentioned by @TimBiegeleisen, +1),

//name

will select all name elements in the document regardless of the root element.

Plosion answered 5/3, 2018 at 3:26 Comment(0)
P
3

Just use the following expression with a relative path:

//name

This seems to capture the two <name> tags you have in your XML sample:

Element='<name>test</name>'
Element='<name>test</name>'
Percyperdido answered 5/3, 2018 at 3:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.