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
Select node by its text value in xmlstarlet
提问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 Value
of a State
based on its Key
equalling state
:
这个 XPath 将根据它的等于选择Value
一个:State
Key
state
/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 WatchingLiveTV
as 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 Key
node. You can do this using the above, but changing the predicate from Value
to Key
:
我只是重新阅读了您原来的问题。您想根据Key
节点的值选择 XML 。您可以使用上述方法执行此操作,但将谓词从 更改Value
为Key
:
//String[Key = 'state']/Value
@kjhughes has put this into the syntax format you're after.
@kjhughes 已将其放入您所追求的语法格式中。
I hope that helps.
我希望这有帮助。