我有一小组固定的节点:<a>
,<b>
,<c>
,<d>
。每个节点的值可以是1或0。
此外,每个节点的权重分别为:1,2,3,4。不使用节点属性。
如何使用XSLT 1.0将每个节点的值乘以其权重?例如:
<a>0</a>
<b>1</b>
<c>0</c>
<d>1</d>
总和:6
<a>1</a>
<b>1</b>
<c>0</c>
<d>0</d>
总和:3
<a>0</a>
<b>1</b>
<c>1</c>
<d>1</d>
总和:9
答案 0 :(得分:3)
不是很优雅,但这就是我想到的。
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my"
exclude-result-prefixes="my">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<my:node-weight>
<node name="a" weight="1"/>
<node name="b" weight="2"/>
<node name="c" weight="3"/>
<node name="d" weight="4"/>
</my:node-weight>
<xsl:template match="root">
<xsl:apply-templates select="*[1]" mode="sum"/>
</xsl:template>
<xsl:template match="*" mode="sum">
<xsl:param name="sumNumber" select="0"/>
<xsl:variable name="thisWeight" select="document('')/*/my:node-weight/node[@name = local-name(current())]/@weight"/>
<xsl:choose>
<xsl:when test="following-sibling::*">
<xsl:apply-templates select="following-sibling::*[1]" mode="sum">
<xsl:with-param name="sumNumber" select="$sumNumber + $thisWeight * number()"/>
</xsl:apply-templates>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$sumNumber + $thisWeight * number()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
当应用于以下格式良好的文档时:
<root>
<a>0</a>
<b>1</b>
<c>0</c>
<d>1</d>
</root>
结果为6
<root>
<a>1</a>
<b>1</b>
<c>0</c>
<d>0</d>
</root>
结果为3
<root>
<a>0</a>
<b>1</b>
<c>1</c>
<d>1</d>
</root>
结果为9
答案 1 :(得分:3)
此XSLT 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:template match="/*">
<xsl:call-template name="sumWeighted"/>
</xsl:template>
<xsl:template name="sumWeighted">
<xsl:param name="pList" select="*"/>
<xsl:param name="pIndex" select="1"/>
<xsl:param name="pAccum" select="0"/>
<xsl:choose>
<xsl:when test="$pIndex > count($pList)">
<xsl:value-of select="$pAccum"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="sumWeighted">
<xsl:with-param name="pList" select="$pList"/>
<xsl:with-param name="pIndex"
select="$pIndex+1"/>
<xsl:with-param name="pAccum"
select="$pAccum+$pList[$pIndex]*$pIndex"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
应用于提供的XML文档:
<t>
<a>0</a>
<b>1</b>
<c>0</c>
<d>1</d>
</t>
,
<t>
<a>1</a>
<b>1</b>
<c>0</c>
<d>0</d>
</t>
和
<t>
<a>0</a>
<b>1</b>
<c>1</c>
<d>1</d>
</t>
分别生成想要的结果:
6
3
9
<强>参考强>:
如果您想通过使用XSLT进行非常复杂的数学计算,请参阅:
<强> http://fxsl.sourceforge.net/articles/xslCalculator/The%20FXSL%20Calculator.html 强>
XPath 2.0 / XSLT 2.0解决方案:
仅使用此XPath 2.0 one-liner:
sum(/*/*/(number()*position()))