Friday, 17 April 2015

split and flatten nodes with XSLT



I cannot have any nested spans, so I need to flatten them and concatenate their class attributes so I can track which classes are parents.


Here's a simplified input:



<p>
ZZZ
<span class="a">
AAA
<span class="b">
BBB
<span class="c">
CCC
</span>
bbb
</span>
aaa
</span>
</p>


Here's the desired output



<p>
ZZZ
<span class="a">
AAA
</span>
<span class="ab">
BBB
</span>
<span class="abc">
CCC
</span>
<span class="ab">
bbb
</span>
<span class="a">
aaa
</span>
</p>


Here's the closest I've come (I'm really new to this, so even getting this far took me a long time...)



<xsl:stylesheet version="1.0"
xmlns:xsl="http://ift.tt/tCZ8VR">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="*/span">
<span class='{concat(../../@class,../@class,@class)}'>
<xsl:value-of select='.'/>
</span>
<xsl:apply-templates/>
</xsl:template>

</xsl:stylesheet>


You can see the result of my failed attempt and how far it is from what I really wanted if you run it yourself. Ideally, I'd like a solution that accepts an arbitrary number of nested levels and can also handle interrupted nests (span, span, notSpan, span...).


No comments:

Post a Comment