【发布时间】:2023-03-21 14:16:02
【问题描述】:
我有这样的xml,
<doc>
<p>20</p>
<p>20</p>
<p>20</p>
<p>100</p>
<t>160</t>
</doc>
包含数字的<p>元素有4个,<t>代表以上4个<p>元素的总和。
我的目标是计算这些<p>元素的百分比并显示。
这是我为它编写的 xsl 代码,
<xsl:variable name="val1" select="abc:get-int-value(doc/p[1]/text())" as="xs:double"/>
<xsl:variable name="val2" select="abc:get-int-value(doc/p[2]/text())" as="xs:double"/>
<xsl:variable name="val3" select="abc:get-int-value(doc/p[3]/text())" as="xs:double"/>
<xsl:variable name="val4" select="abc:get-int-value(doc/p[4]/text())" as="xs:double"/>
<xsl:variable name="valTotal" select="abc:get-int-value(doc/t/text())" as="xs:double"/>
<xsl:variable name="precentage1" select="round(($val1 div $valTotal)*100)" as="xs:double"/>
<xsl:variable name="precentage2" select="round(($val2 div $valTotal)*100)" as="xs:double"/>
<xsl:variable name="precentage3" select="round(($val3 div $valTotal)*100)" as="xs:double"/>
<xsl:variable name="precentage4" select="round(($val4 div $valTotal)*100)" as="xs:double"/>
<xsl:template match="doc">
<xsl:value-of select="$precentage1"/>
<xsl:text> </xsl:text>
<xsl:value-of select="$precentage2"/>
<xsl:text> </xsl:text>
<xsl:value-of select="$precentage3"/>
<xsl:text> </xsl:text>
<xsl:value-of select="$precentage4"/>
</xsl:template>
<xsl:function name="abc:get-int-value" as="xs:double">
<xsl:param name="text" as="xs:string"/>
<xsl:analyze-string select='$text' regex='\d+'>
<xsl:matching-substring>
<xsl:sequence select="number(.)"/>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:function>
但是,它给出的百分比值是 13、13、13 和 63。所以这些数字的总和是 102。(字面意思应该是 100、99 或 101)。似乎 p[4] 的百分比值已四舍五入到 63 而不是 62。
为什么会发生这种情况,我该如何解决?
【问题讨论】: