Select 节点在 xmlstarlet 中的文本值

Select node by its text value in xmlstarlet

我正在尝试提取 'Value' 节点的值,其中 'Key' 节点在 bash shell 中 'state':

<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>

如果我直接引用节点,我可以提取值:

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

但我想 select 它由 'Key' 节点的值代替

我能够使用以下 XPath 找到该节点:

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

哪个会 return:

<Value>WatchingLiveTV</Value>

请注意,您还可以使用:

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

稍微小一点。

要 select 值元素和 parent/siblings,您可以使用:

//String[Value = 'WatchingLiveTV']

哪个 returns:

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

编辑

我刚刚重新阅读了您的原始问题。您希望根据 Key 节点的值 select XML。您可以使用上面的方法来执行此操作,但是将谓词从 Value 更改为 Key:

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

@kjhughes 已将其放入您想要的语法格式中。

希望对您有所帮助。

此 XPath 将 select Value of a State 基于其 Key 等于 state:

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

或者,在 xmlstarlet 中:

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

将returnWatchingLiveTV按要求。