Ogbechi
Ogbechi

Reputation: 53

How to get attribute value by another attribute with xmllint

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

Upvotes: 3

Views: 6360

Answers (2)

Jens Erat
Jens Erat

Reputation: 38682

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.

Upvotes: 3

Mark Veenstra
Mark Veenstra

Reputation: 4739

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

Upvotes: 1

Related Questions