3

I've a XML document like this:

<items>
  <item id="1" name="CP_09550"/>
  <item id="2" name="CP_09551"/>
  <item id="3" name="CP_09552"/>
</items>

How can I get the id value with the name parameter for ex: CP_09550 in xmllint?

Thanks

Ogbechi
  • 53
  • 1
  • 3
  • 7

2 Answers2

3

To fetch the value, wrap the XPath expression into a string(...) or number(...) function call:

xmllint --xpath 'string(/items/item[@name="CP_09550"]/@id)' test.xml

This will return exactly 1, so no need to further process the output in a script.

Jens Erat
  • 37,523
  • 16
  • 80
  • 96
  • What about if I have a variable number of elements before items? – user2284570 Nov 02 '14 at 11:28
  • Sorry, I don't get your question. Better ask a new question referencing this one (if this is similar), and add example input and expected output. If you add a link here, I'll have a look at it. – Jens Erat Nov 02 '14 at 14:14
1

This XPath extracts the wanted ID:

/items/item[@name='CP_09550']/@id

If I execute this in xmllint from the prompt I need to escape the quotes:

xmllint --xpath /items/item[@name=\'CP_09550\']/@id test.xml
Mark Veenstra
  • 4,691
  • 6
  • 35
  • 66
  • 3
    Better just quote the XPath expression: `xmllint --xpath '/items/item[@name="CP_09550"]/@id' test.xml`. – Jens Erat Feb 27 '14 at 17:53