Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use xslt to change only a few XML elements while leaving everything else the same

Tags:

xml

xslt

I have the following problem with XSLT.

In an XML document I have several <h></h> tags embedded within different levels of <div></div> tags.

In effort to change all the <h></h> to <h1></h1> <h2></h2> <h3></h3> respective to where the fall within the different div sections I have written the following XSLT script.

<xsl:template match="//TU:div/TU:h">
    <h1><xsl:apply-templates/></h1>
</xsl:template>

<xsl:template match="//TU:div/TU:div/TU:h">
    <h2><xsl:apply-templates/></h2>
</xsl:template>

And so on. . . . The problem is that I want everything else to stay exactly the same. I only want the <h></h> tags to change.

Unfortunately, when I process the document, the <h></h> tags change as desired, but all other elements go away.

Is there another solution to this problem besides simply writing an <xsl:template> for each element, so that every given element will be replaced with itself?

For example for the element <p></p>:

<xsl:template match="//TU:p">
    <p><xsl:apply-template/></p>
</xsl:template>

Do I need to do something like that to preserve each element, or is there a better way?

Thanks for your help.

like image 644
Jeff Avatar asked Jul 22 '11 16:07

Jeff


1 Answers

Add the identity template to match everything else...

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="TU:h">
  <xsl:variable name="id" select="count(ancestor::TU:div)" />
  <xsl:element name="h{$id}" namespace="TUSTEP">
     <xsl:apply-templates select="@* | node()" />
  </xsl:element>
</xsl:template>
like image 170
Bob Vale Avatar answered Nov 08 '22 05:11

Bob Vale