使用Bash从XML属性获取注释标签 [英] Get comment tag from XML attribute with Bash
问题描述
我了解如何在常规节点中检索XML内容,但是我想了解如何使用Bash在XML的注释标签中检索内容.
I understand how to retrieve XML content within regular nodes, but I would like to understand how to retrieve content within a comment tag in XML using Bash.
例如,考虑以下XML代码段:
For example, consider the below XML snippet:
<ParentTag1><!--This comment is associated to ParentTag1 -->
<ChildTag1>ChildTag1Blah</ChildTag1><!-- ChildTag1 comment-->
<ChildTag2><!-- ChildTag2 comment -->
<GrandchildTag1>GrandchildTag1Blah</GrandchildTag1><!-- GrandchildTag1 comment-->
<GrandchildTag2>GrandchildTag2Blah</GrandchildTag2><!-- GrandchildTag2 comment-->
</ChildTag2>
</ParentTag1>
我想知道如何检索与该节点相关的注释.例如,给定 ParentTag1
,我可以运行什么命令来检索此注释与ParentTag1相关联"注释?对于其他节点也是如此.
I'd like to know how to retrieve the comment associated to the node in question. For example, given ParentTag1
, what command can I run to retrieve the "This comment is associated to ParentTag1" comment? Similarly for the other nodes.
我过去曾经使用 xmlstarlet
来检索节点中的内容,但是我不确定是否会使用相同的内容来检索XML注释中的内容.
I have used xmlstarlet
in the past to retrieve content within the nodes, but I'm not entirely sure if the same would be used to retrieve content within a comment in XML.
推荐答案
要检索注释,请使用 comment()
节点选择器.
要获取此评论与ParentTag1相关联"的评论,您可以使用
The retrieve comments, use the comment()
node selector.
To get the "This comment is associated to ParentTag1" comment you can use
xmlstarlet sel -t -v "//ParentTag1/comment()[1]" input.xml
要从所有后代注释中进行选择,请使用 descendant :: comment()
轴
To chose from all descendant comments, use the descendant::comment()
axis like this
xmlstarlet sel -t -v "//ParentTag1/descendant::comment()" input.xml
结果是:
This comment is associated to ParentTag1
ChildTag1 comment
ChildTag2 comment
GrandchildTag1 comment
GrandchildTag2 comment
此后,您可以索引所需的注释(或使用另一个轴).
After that, you can index the comment you want (or use another axis).
这篇关于使用Bash从XML属性获取注释标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!