I can’t figure out how to find nested elements of the same type. Typically, if I have 7 levels of headers and want to transform them with XSLT to h1–h7 heads, how to choose them with XPath—I can’t make out nothing better than div/div/div/head but this seems really clumsy.
1 Answer
This transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="div/head">
<xsl:element name="h{count(ancestor::div)}">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
when applied on this XML document:
<div>
<head>1</head>
<div>
<head>2-1</head>
<div>
<head>3-1</head>
</div>
</div>
<div>
<head>2-2</head>
</div>
</div>
produces the wanted, correct result:
<div>
<h1>1</h1>
<div>
<h2>2-1</h2>
<div>
<h3>3-1</h3>
</div>
</div>
<div>
<h2>2-2</h2>
</div>
</div>
1 Comment
Honza Hejzl
Wow, not so easy as I would have thought! Very interesting, thanks a lot.