Reputation: 1306
Let's say I have the following Xml,
<Image>
<page name="img031.jpg" indexDoc="1" />
<page name="img045.jpg" indexDoc="2" />
<page name="img033.jpg" indexDoc="1" />
<page name="img071.jpg" indexDoc="3" />
<page name="img091.jpg" indexDoc="1" />
<page name="img021.jpg" indexDoc="2" />
<page name="img991.jpg" indexDoc="1" />
</Image>
I'm using the following XSL
<?xml version="1.0" encoding="iso-8859-1"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="id_doc" match="page" use ="@indexDoc"/>
<xsl:template match = "Image">
<Folder>
<xsl:apply-templates select="page[generate-id(.)=generate-id(key('id_doc', @indexDoc)[1])]"/>
</Folder>
</xsl:template>
<xsl:template match="page">
<Document>
<xsl:for-each select="key('id_doc', @indexDoc)">
<Page>
<xsl:attribute name="nom">
<xsl:value-of select="@name"/>
</xsl:attribute>
<xsl:attribute name="indexDocument">
<xsl:value-of select="@indexDoc"/>
</xsl:attribute>
</Page>
</xsl:for-each>
</Document>
</xsl:template>
</xsl:stylesheet>
In order to group the page nodes based on their indexDoc attribute, while also creating new nodes <Folder>
and <Document>
I'm getting The following result :
<Folder>
<Document>
<Page nom="img031.jpg" indexDocument="1"/>
<Page nom="img033.jpg" indexDocument="1"/>
<Page nom="img091.jpg" indexDocument="1"/>
<Page nom="img991.jpg" indexDocument="1"/>
</Document>
<Document>
<Page nom="img045.jpg" indexDocument="2"/>
<Page nom="img021.jpg" indexDocument="2"/>
</Document>
<Document>
<Page nom="img071.jpg" indexDocument="3"/>
</Document>
</Folder>
But I'am a bit lost on how to get the count of the Node <Document>
since it is created after the transformation, I want to get this value as attribute of the node <Folder nbrDocuments="3">
So I was thinking to either count distinct indexDoc attribute values which equals the <Document>
node count, or to retransform the resulting xml once again in order to get the count of nodes,
I'm not sure how effecient any of two the solutions are, so I'm wondering if there is a better way to approach this issue.
Upvotes: 0
Views: 119
Reputation: 117140
Instead of:
<xsl:template match = "Image">
<Folder>
<xsl:apply-templates select="page[generate-id(.)=generate-id(key('id_doc', @indexDoc)[1])]"/>
</Folder>
</xsl:template>
try:
<xsl:template match="/Image">
<xsl:variable name="documents" select="page[generate-id(.)=generate-id(key('id_doc', @indexDoc)[1])]"/>
<Folder nbrDocuments="{count($documents)}">
<xsl:apply-templates select="$documents"/>
</Folder>
</xsl:template>
Upvotes: 1