首页 > 解决方案 > 使用 Bash 从 XML 属性中获取注释标记

问题描述

我了解如何在常规节点中检索 XML 内容,但我想了解如何使用 Bash 在 XML 中的评论标签中检索内容。

例如,考虑以下 XML 片段:

    <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 相关联”评论?对于其他节点也是如此。

我过去曾使用xmlstarlet过检索节点内的内容,但我不完全确定是否可以使用相同的方式检索 XML 中的评论中的内容。

标签: xmlbashshell

解决方案


检索评论,使用comment()节点选择器。
要获得“此评论与 ParentTag1 相关联”评论,您可以使用

xmlstarlet sel -t -v "//ParentTag1/comment()[1]" input.xml

要从所有后代评论中进行选择,请使用这样的descendant::comment()

xmlstarlet sel -t -v "//ParentTag1/descendant::comment()" input.xml

结果是:

This comment is associated to ParentTag1 
ChildTag1 comment
ChildTag2 comment 
GrandchildTag1 comment
GrandchildTag2 comment

之后,您可以索引您想要的评论(或使用另一个轴)。


推荐阅读