[英]How I can count distinct-values with xslt and XPath 2.0
我想獲取一個不同值的列表並計算金額的總和。
我的xml是:
<root>
<orders>
<fileid>123456789</fileid>
<order>
<name>Max Mustermann</name>
<street>Musterstr. 5</street>
<zip>12345</zip>
<city>Munster</city>
<articles>
<article>
<name>Vase</name>
<articlenumber>1234-001</articlenumber>
<amount>2</amount>
</article>
</articles>
</order>
<order>
<name>Karin Müller</name>
<street>Hofstr. 25</street>
<zip>54321</zip>
<city>Hamburg</city>
<articles>
<article>
<name>Blumen</name>
<articlenumber>4321-003</articlenumber>
<amount>10</amount>
</article>
</articles>
</order>
<order>
<name>Jenni Schulz</name>
<street>Achenerstr. 7</street>
<zip>34567</zip>
<city>Achen</city>
<articles>
<article>
<name>Tischdecke</name>
<articlenumber>4711-001</articlenumber>
<amount>1</amount>
</article>
<article>
<name>Vase</name>
<articlenumber>1234-001</articlenumber>
<amount>4</amount>
</article>
</articles>
</order>
</orders>
</root>
我想要這個清單:
<articles>
<article>
<name>Vase</name>
<articlenumber>1234-001</articlenumber>
<amount>6</amount>
</article>
<article>
<name>Blumen</name>
<articlenumber>4321-003</articlenumber>
<amount>10</amount>
</article>
<article>
<name>Tischdecke</name>
<articlenumber>4711-001</articlenumber>
<amount>1</amount>
</article>
</articles>
從3個訂單中有4篇文章,我想用xslt翻譯一個列表,僅列出所有訂單中所有金額之和的文章。 在此列表中,文章應有所區別。 您可以在文章“花瓶”中看到這一點。 這是2個訂單,金額從2到4。在我的目標列表中,“花瓶”條款只有一次,金額從6開始。所有訂單的總和。
我讀了很多書,可以得到不同的商品名稱或商品編號列表,但是每次我都無法合並所有需要的值。 您有想法可以幫助我嗎? 謝謝
使用XSLT 2.0,這是一個要用for-each-group
解決的分組問題:
<xsl:template match="/">
<articles>
<xsl:for-each-group select="//articles/article" group-by="articlenumber">
<xsl:copy>
<xsl:copy-of select="* except amount"/>
<amount><xsl:value-of select="sum(current-group()/amount)"/></amount>
</xsl:copy>
</xsl:for-each-group>
</articles>
</xsl:template>
有關完整的示例,請參見http://xsltransform.net/3NzcBt8 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.