是否可以使用 xmlstarlet 或其他 bash 工具在 xml 文件中添加 comment/uncomment 标签

Is it possible to comment/uncomment tags inside an xml file using xmlstarlet or other bash tools

如何使用 xmlstarlet 或任何其他 shell 脚本 libraries/tools 等以编程方式在 xml 文件中 comment/uncomment 标记块

评论中...

输入文件:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

输出文件:

<note>
<to>Tove</to>
<!-- <from>Jani</from> -->
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

正在取消注释...

输入文件:

<note>
<to>Tove</to>
<!-- <from>Jani</from> -->
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

输出文件:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

可以用 xsltproc 完成

xsltproc  comment-from.xslt  input.xml

评论-from.xslt

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <!--Identity template,
    provides default behavior that copies all content into the output -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <!--More specific template for "from" that provides custom behavior -->
  <xsl:template match="from">
    <xsl:comment>
      <xsl:text><![CDATA[ <from>]]></xsl:text>
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
      <xsl:text><![CDATA[</from> ]]></xsl:text>
    </xsl:comment>
  </xsl:template>
</xsl:stylesheet>

玩过 xlstproc 后,我想出了一个取消注释案例的解决方案。 'contains' 函数可以解决问题...

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!--Identity template,
   provides default behavior that copies all content into the output -->
   <xsl:template match="@*|node()">
       <xsl:copy>
           <xsl:apply-templates select="@*|node()"/>
       </xsl:copy>
   </xsl:template>
   <!--More specific template for "from" that provides custom behavior -->
   <xsl:template match="comment()">

       <xsl:if test='contains(.,"&lt;from&gt;")' >
           <xsl:value-of  select="." disable-output-escaping="yes" />
       </xsl:if>

       <xsl:if test='not (contains(.,"&lt;from&gt;"))' > 
           <xsl:copy-of select="." />
       </xsl:if>

   </xsl:template>
</xsl:stylesheet>