Reputation: 83
I would need to understand how I can get the position of a parallel element with similar value in a sub-element selected with XSL. I have item lines listed with certain reference as sub-element and then I have sub-item lines, which should be linked into item-lines based on the sub-element value. Sub-item lines should indicate the position of item-lines with similar reference
I have tried several different preceeding approaches with different conditions in brackets [ ] , but so far without luck. I can use only xslt 1.0
I have xml with structure like this:
<goods>
<item>
<ref>a</ref>
</item>
<item>
<ref>b</ref>
</item>
<item>
<ref>c</ref>
</item>
<item>
<ref>d</ref>
</item>
<subitem>
<subref>c</subref>
</subitem>
<subitem>
<subref>a</subref>
</subitem>
</goods>
and my xsl (1.0) :
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="text" version="1.0" encoding="ISO-8859-1" indent="yes"/>
<xsl:template match="/">
<xsl:call-template name="Line"/>
</xsl:template>
<xsl:template name="Line">
<xsl:for-each select="goods/item">
<xsl:value-of select="position()"/>
<xsl:text>;</xsl:text>
<xsl:value-of select="ref"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
<xsl:for-each select="goods/subitem">
<xsl:text>0;</xsl:text>
<xsl:value-of select="subref"/>
<xsl:text>;</xsl:text>
here would be some kind of conditional preceeding select needed
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The desired output would be:
1;a
2;b
3;c
4;d
0;c;3
0;a;1
where 2 last lines are sub-items and the last number should tell me the position of item-element, where the same reference is. In example reference 'c' is inside item element with position 3 (third item-element has 'c' in sub-element 'ref') so subitem with subref value 'c' should be linked to item position 3 in example.
Same would go with each subitem lines: all with subitem/subref = a should have position 1, all with 'b' position 2 etc.
Upvotes: 1
Views: 340
Reputation: 117175
Here's one way you could look at it:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:key name="item" match="item" use="ref" />
<xsl:template match="/goods">
<xsl:for-each select="item">
<xsl:value-of select="position()" />
<xsl:text>;</xsl:text>
<xsl:value-of select="ref"/>
<xsl:text>
</xsl:text>
</xsl:for-each>
<xsl:for-each select="subitem">
<xsl:text>0;</xsl:text>
<xsl:value-of select="subref"/>
<xsl:text>;</xsl:text>
<xsl:value-of select="count(key('item', subref)/preceding-sibling::item) +1" />
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Note that this assumes that every subref
has a corresponding item
with matching ref
value.
Upvotes: 2