Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSL: Copy XML and then replace some tags

Tags:

xml

xslt

I am very new to XSL/XSLT. I want to copy an xml document into an other but replace some namespaced tags and some tags that have some special attributes. For example:

<root>
  <ext:foo>Test</ext:foo>
  <bar>Bar</bar>
  <baz id="baz" x="test">
    <something/>
  </baz>
</root>

Should be rewritten into:

<root>
  --Test--
  <bar>Bar</bar>
  xxx<baz id="baz">
    <something/>
  </baz>xxx
</root>

Is it possible to copy the whole XML and then apply some rules to replace the tags I want to replace?

like image 715
stofl Avatar asked Oct 04 '11 17:10

stofl


1 Answers

You can copy some nodes and re-write others with different rules. To keep <root> and <bar> the same, and re-write <baz>, try this (untested) as a starting point:

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

  <!-- Match <baz> and re-write a little -->
  <xsl:template match="baz">
    xxx<baz id="{@id}">
     <xsl:apply-templates />
    </baz>xxx
  </xsl:template>

  <!-- By default, copy all elements, attributes, and text -->
  <xsl:template match="@* | node()">
<xsl:copy>
  <xsl:apply-templates select="@* | node()"/>
</xsl:copy>
  </xsl:template>


</xsl:stylesheet>
like image 86
Carl Raymond Avatar answered Oct 13 '22 23:10

Carl Raymond