简体   繁体   中英

xmlstartlet how can I insert <!— comment --> line above node

I want to add a commentline inside a xml file above the node using xmlstartlet

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

I like to achieve this:

<?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>

I tried:

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

But gives error -bash: :--xml created by Stackoverflow--: event not found

hope someone can help.

The following is an XSLT-1.0 and above solution that can be applied by xsltproc or any other XSLT processor:

<?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>

Output should be as expected.
If you could use XSLT-3.0, the identity template could be replaced by

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM