Reputation: 129
I'm quite new to XSLT and I'm using XSLT 1.0. Now I need to group some stuff in a quite big XML file. There are lots of examples out there but none worked for me for some reason. I'm able to group the info I want, but I also get some extra text in my output xml. Here's what I'm doing right now;
Input XML (this is a temp XML, actual input is quite bigger but I will be able to apply the same to my real xml too)
<?xml version="1.0" encoding="utf-8"?>
<objects>
<groupNumber>15</groupNumber>
<object>
<items>
<item>
<itemOptions>
<itemNumber>1</itemNumber>
</itemOptions>
</item>
<item>
<itemOptions>
<itemNumber>1</itemNumber>
</itemOptions>
</item>
<item>
<itemOptions>
<itemNumber>2</itemNumber>
</itemOptions>
</item>
<item>
<itemOptions>
<itemNumber>3</itemNumber>
</itemOptions>
</item>
<item>
<itemOptions>
<itemNumber>3</itemNumber>
</itemOptions>
</item>
</items>
</object>
</objects>
Now I want to group the items by their itemNumbers. Here's what I do;
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs xsi xsl">
<xsl:output method="xml" encoding="UTF-8" indent="yes"/>
<xsl:key name="itemler" match="item" use="itemOptions/itemNumber" />
<xsl:template match="items" name="temp">
<numbers>
<xsl:for-each select="item[count(. | key('itemler', itemOptions/itemNumber)[1])=1]">
<number>
<xsl:value-of select="itemOptions/itemNumber" />
</number>
</xsl:for-each>
</numbers>
</xsl:template>
</xsl:stylesheet>
With this code, I'm getting this output;
<?xml version="1.0" encoding="utf-8"?>
15
<numbers>
<number>1</number>
<number>2</number>
<number>3</number>
</numbers>
Which is almost exactly what I want, except the "15". I get the grouped numbers AND a value from tag which is under root.
I'm getting this exactly same error when I try to apply this XSLT to my main XML, I get what I want with lots of unwanted info from tags under root and some other tags. What is the problem here?
I'm guessing it's something related to templates or matches but I really have no idea how to solve.
Thank you very much.
Upvotes: 0
Views: 380
Reputation: 167716
Add a template doing
<xsl:template match="/">
<xsl:apply-templates select="//items"/>
</xsl:template>
to ensure you process only the items
elements.
Upvotes: 1