1

With the xpath /levels/level[@id="3"]/value I can get the value of level where id=3 like this:

<levels> <level id="2"> <value>25</value> </level> <level id="3"> <value>33</value> </level> <level id="4"> <value>44</value> </level> </levels> 

but the XML I am reading is formatted without attributes like this:

<levels> <level> <id>2</id> <value>25</value> </level> <level> <id>3</id> <value>33</value> </level> <level> <id>4</id> <value>44</value> </level> </levels> 

What is the equivalent xpath for this second XML block which will get the value of level where id=3? (It is not guaranteed that id=3 will always be the second node.)

2
  • Your XML is not valid. It contains an extra unclosed <level> element Commented Apr 25, 2013 at 11:50
  • thanks, fixed for clarity sakes :-) Commented Apr 25, 2013 at 13:28

2 Answers 2

2

How about the following:

/levels/level[id/text() = "3"]/value 

or

/levels/level[id/. = "3"]/value 
Sign up to request clarification or add additional context in comments.

Comments

1

Simpler/shorter:

/*/*[id = 3]/value 

2 Comments

+1 Nice shorter example @Dimitre. I still like to use explicit path syntax, but that's just my preference.
@Garett, You are welcome. Location steps with full paths are good for education purposes. Using the abbreviated syntax above isn't just "another syntax" -- its evaluation is slightly more efficient (as the element names aren't verified).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.