Use xslt to change only a few XML elements, leaving everything else

I have the following problem with XSLT.

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

In an attempt to change everything <h></h> to <h1></h1> <h2></h2> <h3></h3> depending on where the fall in different div sections, I wrote 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 be exactly the same. I want the <h></h> tags to change.

Unfortunately, when processing a document, the <h></h> tags change as desired, but all other elements disappear.

Is there any other solution to this problem besides simply writing <xsl:template> for each element, so that each given element will be replaced by itself?

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

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

Do I need to do something to save each item, or is there a better way?

Thank you for your help.

+4
source share
2 answers

Add an 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> 
+8
source

Try creating a generic template as follows:

 <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates/> </xsl:element> </xsl:template> 
0
source

All Articles