【问题标题】:xmlstartlet how can I insert <!--- comment --> line above nodexmlstarlet 如何在节点上方插入 <!--- 注释 --> 行
【发布时间】:2021-03-21 19:44:37
【问题描述】:

我想在节点上方的 xml 文件中添加注释行 使用 xmlstartlet

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book>
      <title lang="en" id="1">Harry Potter</title>
      <price>29.99</price>
    </book>
  </bookstore>

我喜欢做到这一点:

<?xml version="1.0" encoding="UTF-8"?>
<!-- xml created by Stackoverflow-->
<bookstore>
    <book>
      <title lang="en" id="1">Harry Potter</title>
      <price>29.99</price>
    </book>
  </bookstore>

我试过了:

xmlstartlet ed -i /bookstore -t text -n <!--xml created by Stackoverflow--> -v "" test.xml

但是给出错误 -bash: !--xml created by Stackoverflow--: event not found

希望有人能提供帮助。

【问题讨论】:

  • 我刚刚再次阅读了xmlstarlet doc,据此,我没有找到任何修改cmets的命令。
  • 不幸的是.. :(还有其他方法可以实现这一目标吗?
  • 您总是可以使用 XSLT 来解决这个问题。看我的回答。

标签: xml xmlstarlet xml-comments


【解决方案1】:

以下是 XSLT-1.0 及以上的解决方案,xsltproc 或任何其他 XSLT 处理器都可以应用:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="no" indent="yes"/>

  <!-- identity template - copies all nodes without modification -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
   </xsl:template>  
  
  <xsl:template match="/">                                     <!-- Match root element -->
    <xsl:comment> xml created by Stackoverflow </xsl:comment>  <!-- Add comment before root element -->
    <xsl:apply-templates select="node()|@*" />                 <!-- Apply identity template (and all other templates) -->
  </xsl:template>

</xsl:stylesheet>

输出应该符合预期。
如果您可以使用 XSLT-3.0,则 身份模板 可以替换为

<xsl:mode on-no-match="shallow-copy" /> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    相关资源
    最近更新 更多