0

I have below a sample XML structure:

<root>
<id>1</id>
<name>abc</name>
<id>2</id>
<name>def</name>
<id>3</id>
<name>ghi</name>
</root>

I am trying to achieve the one single following job:

Retrieve the text value of the last occurrence of an id tag in the structure. (Should output 3 in this case).

Can you please help?

I have tried using sed but could not get it to output 3. :D

user192234
  • 123
  • 7
Jazz
  • 35
  • 6

1 Answers1

2

You can use xpath queries that traverse an XML file or string.

For example:

xpath -q -e '//root/id[last()]/text()' file.xml

xpath

is an executable/command that takes a query and an XML.

-q stands for quiet, meaning you only get what you asked for in the stdout.

-e comes right before a query string.

// stands for a root to start searching.

last() is what you'd expect -1 to do :).

text() takes only the value and doesn't print it surrounded by tags.

user192234
  • 123
  • 7