Divesh Rastogi
Divesh Rastogi

Reputation: 49

How to convert content between two patterns into specific format using shell

How do we convert the content between 2 patterns into specific format using shell code? The following sample XML that starts with <Mapping> and ends with </Mapping> needs to be converted to plan format code as shown below.

Sample input code:

 <Mapping name="temp1">   /*rule name will the value of Mapping name*/
               <phpCode>
                   boolean_out = copyfunc temp  /*rule content output */
               </phpCode>
 </Mapping>

The value of name will be the rule name and the value of boolean_out will be rule content.

Sample output code:

rule temp1 { // temp1 is the mapping value
  copyfunc temp //boolean_out  value is rule content
}

Upvotes: 0

Views: 59

Answers (1)

kbulgrien
kbulgrien

Reputation: 4518

Given input.xml containing:

<Mapping name="temp1">   /*rule name will the value of Mapping name*/
              <phpCode>
                   boolean_out = copyfunc temp  /*rule content output */
              </phpCode>
</Mapping>

And transform.xsl containing:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="text" encoding="utf-8" indent="no" />

<xsl:template match="Mapping">
  <xsl:text>rule </xsl:text>
  <xsl:value-of select="@name" />
  <xsl:text> { // </xsl:text>
  <xsl:value-of select="@name" />
  <xsl:text> is the mapping value</xsl:text>
  <xsl:apply-templates select="./phpCode" mode="php-code" />
  <xsl:text>&#x0a;}&#x0a;</xsl:text>
</xsl:template>

<xsl:template match="*" mode="php-code">
  <xsl:text>&#x0a;  </xsl:text>
  <xsl:value-of select="substring-before(substring-after(normalize-space(text()),'= '),'/*')" />
  <xsl:text>//</xsl:text>
  <xsl:value-of select="substring-before(normalize-space(text()),'=')" />
  <xsl:text> value is rule content</xsl:text>
</xsl:template>

</xsl:stylesheet>

An XSLT transform produces:

rule temp1 { // temp1 is the mapping value
  copyfunc temp //boolean_out  value is rule content
}

The method of invoking the transform is platform and tool-specific. Command line tools can be used to invoke a transformation, though there are any number of ways to run the XSL script. For example, an xsltproc command is:

xsltproc transform.xsl input.xml

One can use msxsl.exe similarly, except that the command arguments are reversed.

Upvotes: 2

Related Questions