0

I have a server running on Linux system, and I want to edit an XML file of Imagemagick.

The file content is:

<policymap>
  <policy domain="..." rights=".." pattern="...." />
  <policy domain="..." rights=".." pattern="...." />
..
..    
</policymap>

So, I want to add this line:

  <policy domain="coder" rights="read | write" pattern="PDF" />

Please how can I do it.

Thank you.

zaki
  • 127
  • 1
  • 10
  • 1
    have you try nano, vim ..? – abestrad Mar 13 '19 at 21:05
  • You can do this automatically with XSLT-1.0 and the _identity template_. – zx485 Mar 13 '19 at 21:06
  • 1
    Possible duplicate of [Grep and Sed Equivalent for XML Command Line Processing](https://stackoverflow.com/q/91791/608639), [Edit XML from command line with shell script on Linux](https://stackoverflow.com/q/17592740/608639), etc. – jww Mar 14 '19 at 00:10

1 Answers1

1

You can do this automatically with an XSLT-1.0 processor and the identity template:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0">
<xsl:output method="xml" />

  <!-- Identity template - in XSLT-3.0 it can be replaced by 
       <xsl:mode on-no-match="shallow-copy"/> 
   -->
  <xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/policymap">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*" />
        <!-- Added new line -->
        <policy domain="coder" rights="read | write" pattern="PDF" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Its output is:

<?xml version="1.0"?>
<policymap>
    <policy domain="..." rights=".." pattern="...."/>
    <policy domain="..." rights=".." pattern="...."/>
    ..
    ..    
    <policy domain="coder" rights="read | write" pattern="PDF"/>
</policymap>

The command on *Ubuntu could be

xsltproc transform.xslt source.xml

or using Saxon:

java -jar saxon9he.jar -xsl:b.xslt b.xml
zx485
  • 28,498
  • 28
  • 50
  • 59