-->

XMLStarlet Return attribute based on value (Revers

2019-08-10 16:35发布

问题:

I have this xml:

<block name="http-www.example.com">
  <mapentry tag="AB12">bottlecap</mapentry>
  <mapentry tag="CD45">description goes here</mapentry>
  <mapentry tag="GH23">12345</mapentry>
  <mapentry tag="JK89">54321</mapentry>
</block>

And I want to find the "tag" based on the value.

So I want to search for "bottlecap" and have it return "AB12"

In all the examples I've seen, people search for the attribute to get the result, but in this type of xml that isn't possible since the nodes and attributes are ambiguous

I've been trying to use -i but that only seems to work on the node or attribute, but not on the value.

xmlstarlet sel -t -i //bottlecap -v "//mapentry[@tag]" "mytest.xml"

Is there a way to search the value?

回答1:

Perhaps this is what you're after?

xmlstarlet sel -t -v "//mapentry[. = 'bottlecap']/@tag" "mytest.xml"