I need to loop a XML document. No problem there.
The problem come when I need text from the previous line I have just skipped.
The XML will look some thing like this
<lines>
<line>
<id>1</id>
<text>Some fancy text here 1</text>
</line>
<line>
<id></id>
<text>This I need in the next line with a ID</text>
</line>
<line>
<id></id>
<text>Also need this.</text>
</line>
<line>
<id>4</id>
<text>Here we go</text>
</line>
</lines>
The output XML file need to look like this
<output>
<line>
<id>1</id>
<note>Some fancy text here 1</note>
</line>
<line>
<id>4</id>
<note>Here we go</note>
<extra>
<note>This I need in the next line with a ID</note>
<note>Also need this.</note>
</extra>
</line>
</output>
The XSL I have so fare is simple to sort out the line that have no ID set.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<output>
<xsl:for-each select="lines/line">
<xsl:if test="id/text() > 0">
<line>
<id>
<xsl:value-of select="id" />
</id>
<note>
<xsl:value-of select="text" />
</note>
</line>
</xsl:if>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>
I did not resist to completely review your code 🙂
Here follows a complete XSLT 1.0 solution more functional-oriented (no procedural approach). It might look at first seen harder to see, but, imho, it’s a very good example to get started into XSLT templating mechanism.
Also using
xsl:for-eachin your specific case is not that easy, because at a certain step of the loop you want to get all preceding adjacent siblings with emptyid, without knowing how many they are a priori.I’ve also used the identity template to simplify the work of recreating your target.
Applied on your input, gives: