Saturday, June 11, 2011

Preceding-Sibling | The Easy Way

Keeping on track with my previous post regarding the preceding-sibling approach to getting unique values with XSL, I prefer to not have to do the Muench method whenever possible. I like to keep it simple. Here is a really simple way to get a unique or distinct list of categories and sub-categories from an xml file:




<xsl:for-each select="item">
<xsl:variable name="thisNodeCategory" select="Category"/>
<xsl:if test="not(preceding-sibling::item[Category=$thisNodeCategory])">
<span class="Category">
<a href="">
<xsl:value-of select="Category" />
</a>
</span>
<br/>
</xsl:if>
<xsl:if test="SubCategory > ''">
<span class="subCategory">
- <a href="">
<xsl:value-of select="SubCategory" />subcategory
</a>
</span>
<br/>
</xsl:if>
</xsl:for-each>

Friday, June 10, 2011

Easier than preceding-sibling::

I don't like to use preceeding-sibling. It doesn't work when I want it to. So, I created a method that works just like it:



This method is a lot easier to implement. But, it doesn't work with <xsl:sort>. It requires the XML be in the correct sort order before doing the XSL Transform. If you don't have this luxury, you can use the method I will post in the following blog post. Or, if you are really brave, you can use the Muench Method. I think I posted how to do that in a previous post. Well, anyway you decide to do it, good luck.




<xsl:variable name="thisChildNode" select="Category"/>
<xsl:variable name="lastNodePosition" select="position() - 1"/>
<xsl:if test="not(/grandParentNode/parentNode[$lastNodePosition]/childNode = $thisChildNode)">
<h2><xsl:value-of select="childNode" /></h2>
</xsl:if>