bash 通过 xmlstarlet 中的文本值选择节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28755179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:26:36  来源:igfitidea点击:

Select node by its text value in xmlstarlet

xmlbashxmlstarlet

提问by SingingDwarf

I am trying to extract the value of the 'Value' node, where the 'Key' node is 'state' within a bash shell:

我正在尝试提取 '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>

I can extract the value if I reference the node directly:

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

$ 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 the 'Key' node instead

但我想通过 'Key' 节点的值来选择它

回答by kjhughes

This XPath will select Valueof a Statebased on its Keyequalling state:

这个 XPath 将根据它的等于选择Value一个:StateKeystate

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

Or, in xmlstarlet:

或者,在 xmlstarlet 中:

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

Will return WatchingLiveTVas requested.

WatchingLiveTV将按要求返回。

回答by Rastus7

I was able to find that node using the following XPath:

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

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

Which will return:

哪个将返回:

<Value>WatchingLiveTV</Value>

Note you could also use:

请注意,您还可以使用:

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

Which is slightly smaller.

哪个稍微小一点。

To select the Value element and parent/siblings, you could use:

要选择 Value 元素和父/兄弟姐妹,您可以使用:

//String[Value = 'WatchingLiveTV']

Which returns:

返回:

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

Edit

编辑

I just re-read your original question. You would like to select the XML based on the value of the Keynode. You can do this using the above, but changing the predicate from Valueto Key:

我只是重新阅读了您原来的问题。您想根据Key节点的值选择 XML 。您可以使用上述方法执行此操作,但将谓词从 更改ValueKey

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

@kjhughes has put this into the syntax format you're after.

@kjhughes 已将其放入您所追求的语法格式中。

I hope that helps.

我希望这有帮助。