我是整个 XSLT 的新手,我已经尝试通过几个论坛查找它,但我仍然没有找到解决我的问题的实际解决方案。
我有以下 XML:
<Cinema>
<Movie name="movie1" in="191" out="191">
<Period time="16:00:00" in="20" out="20"/>
<Period time="18:00:00" in="71" out="70"/>
<Period time="20:00:00" in="100" out="101"/>
</Movie>
<Movie name="movie2" in="105" out="105">
<Period time="16:00:00" in="13" out="13"/>
<Period time="18:00:00" in="34" out="34"/>
<Period time="20:00:00" in="58" out="58"/>
</Movie>
<Movie name="movie3" in="247" out="247">
<Period time="16:00:00" in="57" out="57"/>
<Period time="18:00:00" in="75" out="72"/>
<Period time="20:00:00" in="115" out="118"/>
</Movie>
</Cinema>
我想要得到的是每个电影时期的总访问量。
例如:
16:00h - in: 90, out: 90
18:00h - in: 180, out: 176
20:00h - in: 273, out: 277
Total - in: 543, out: 543
我尝试为每个循环嵌套,但我无法真正弄清楚如何在这种示例中使用它,因为 XSLT 不接受我实际上习惯的可变变量(过程编程)。
有人对我有这个问题的简单解决方案吗?提前致谢!
最佳答案
您可以使用 sum
功能。
XSTL 1.0 解决方案:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:key name="k" match="Period" use="@time"/>
<xsl:template match="/Cinema">
<xsl:apply-templates select="//Period[generate-id(.) = generate-id(key('k', @time))]"/>
<xsl:value-of select="concat('Total - in: ', sum(Movie/@in), ', out: ', sum(Movie/@out))"/>
</xsl:template>
<xsl:template match="Period">
<xsl:value-of select="
concat(substring(@time, 1, 5), 'h - in: ',
sum(key('k', @time)/@in),
', out: ',
sum(key('k', @time)/@out))"/>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
输出:
16:00h - in: 90, out: 90
18:00h - in: 180, out: 176
20:00h - in: 273, out: 277
Total - in: 543, out: 543
它使用 Muenchian 方法进行分组。引用:http://www.jenitennison.com/xslt/grouping/muenchian.html
// is short for /descendant-or-self::node()/. For example, //para is short for /descendant-or-self::node()/child::para and so will select any para element in the document (even a para element that is a document element will be selected by //para since the document element node is a child of the root node); div//para is short for div/descendant-or-self::node()/child::para and so will select all para descendants of div children.
引用:http://www.w3.org/TR/xpath/#path-abbrev
关于xml - XSLT - XML中每个元素中每个属性的总和与for-each?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7468085/