问题
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.
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>
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.
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.
回答1:
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
To chose from all descendant comments, use the descendant::comment() axis like this
xmlstarlet sel -t -v "//ParentTag1/descendant::comment()" input.xml
Result is:
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).
来源:https://stackoverflow.com/questions/58080572/get-comment-tag-from-xml-attribute-with-bash