Select node by its text value in xmlstarlet

I am trying to extract the value "value" of the node, where the "key" of the node is a "state" in the bash shell:

<FrontendStatus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" serializerVersion="1.1">
<script/>
 <State>
  <String>
   ...
   ...
  </String>
  <String>
   ...
   ...
  </String>
  <String>
   <Key>state</Key>
   <Value>WatchingLiveTV</Value>
  </String>
  <String>
   <Key>studiolevels</Key>
   <Value>1</Value>
  </String>
  <String>
   ...
   ...
  </String>
  <String>
   ...
   ...
  </String>
 </State>
</FrontendStatus>

I can extract the value if I refer directly to node:

$ xmlstarlet sel -t -m '/FrontendStatus[1]/State[1]/String[31]' -v Value <status.xml
WatchingLiveTV

But I would like to select it by the value of "Key" node instead

+4
source share
2 answers

This XPath will select Valuefor Statebased on it Keyequal to State:

/FrontendStatus/State/String[Key='state']/Value

Or in xmlstarlet:

$ xmlstarlet sel -t -m "/FrontendStatus/State/String[Key='state']" -v Value <status.xml

Will return WatchingLiveTVas requested.

+5
source

I managed to find the node using the following XPath:

/FrontendStatus/State/String[Value = 'WatchingLiveTV']/Value

What will return:

<Value>WatchingLiveTV</Value>

Note that you can also use:

//String[Value = 'WatchingLiveTV']/Value

This is a little less.

Value parent/siblings, :

//String[Value = 'WatchingLiveTV']

:

<String>
  <Key>state</Key>
  <Value>WatchingLiveTV</Value>
</String>

Edit

. XML Key node. , , Value Key:

//String[Key = 'state']/Value

@kjhughes , .

, .

0