Dan
Dan

Reputation: 536

Select the last occurrence of a group of nodes XSLT

I need to find the last occurrence of a group of prices (which are the totals). These prices will always have a decimal in them (.)

Their text values are stored in nodes, and they they are found as the last occurrence of 3 nodes that all contain '.'.

Example XML:

<?xml version="1.0" encoding="UTF-16"?>
<?xml-stylesheet type="text/xsl" href="XSLT.xsl"?>
<document xmlns="http://www.scansoft.com/omnipage/xml/ssdoc-schema3.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<part1>
    <prices>
        <wd>3.1</wd>
        <wd>56.4</wd>
        <wd>134.4</wd>
    </prices>
    <prices2>
        <wd>1,330.2</wd>
        <wd>23.14</wd>
        <wd>124.7</wd>
    </prices2>
</part1>
</document>

My attempt at finding the final group is as follows. However I can't get it to compile, yet alone work.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
         xmlns:ss="http://www.scansoft.com/omnipage/xml/ssdoc-schema3.xsd">
  <xsl:output method="text" />

 <xsl:template match="/"> 

<xsl:variable name="LastGroup" select="//ss:wd[(contains(.,'.') and (following::ss:wd[contains(.,'.')]) and (following::ss:wd[contains(.,'.')][2])][last()]"/>

<xsl:for-each select="$LastGroup">
    <xsl:value-of select="."/>
    <xsl:value-of select="following::ss:wd"/>
    <xsl:value-of select="following::ss:wd[2]"/>
</xsl:for-each>

</xsl:template>
</xsl:stylesheet>

I'm using XSLT 1.0

Upvotes: 0

Views: 729

Answers (1)

Eric van der Vlist
Eric van der Vlist

Reputation: 857

If you want to strictly follow the algorithm that you've described you can declare your variable as:

<xsl:variable name="LastGroup"
  select="(//ss:wd[contains(.,'.') and contains(following::ss:wd[1],'.') and contains(following::ss:wd[2],'.')])[last()]"/>

Note that this will be slow for big files, especially because you are using the following:: axis. If these three elements are always embedded in the same parent as shown in your sample, replacing following:: by following-sibling:: should improve the performance... Replacing //ss:wd by something more selective should also help.

Upvotes: 1

Related Questions