0

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.

zx485
  • 28,498
  • 28
  • 50
  • 59
GJF
  • 77
  • 7

1 Answers1

0

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" /> 
zx485
  • 28,498
  • 28
  • 50
  • 59