我在此示例文件中有减法问题:
<EVENTS>
<ROW ID="204" ID_PLACE="1" EVENT_TYPE="B" EVENT_NAME="TEST1" EVENT_ID="201">
<PRICE>
<ROW EVENT_PRICE="165,00"/>
</PRICE>
</ROW>
<ROW ID="205" ID_PLACE="1" EVENT_TYPE="P" EVENT_NAME="TEST1" EVENT_ID="201">
<PRICE>
<ROW EVENT_PRICE="125,00"/>
</PRICE>
</ROW>
</EVENTS>
她是我的XSLT的相关部分:
<xsl:for-each select="EVENTS/ROW/PRICE/ROW">
<xsl:variable name="event_b">
<xsl:choose>
<xsl:when test="EVENT_TYPE=B">
<xsl:value-of select="EVENT_PRICE" />
</xsl:when>
</xsl:choose>
</xsl:variable>
<xsl:variable name="event_p">
<xsl:choose>
<xsl:when test="EVENT_TYPE=P">
<xsl:value-of select="EVENT_PRICE" />
</xsl:when>
</xsl:choose>
</xsl:variable>
<xsl:value-of select="number($event_b) - number($event_p)" />
</xsl:for-each>
我必须从类型为B的相应类型中减去带有类型P的event_price。在此示例中,我想获得结果40,并将其输出到结果树中,但它不起作用。怎么了?
答案 0 :(得分:0)
您正在尝试将字符串转换为数字,但这些字符串的格式不正确,不适用于XSL / XPath / XSI编号。具体来说,number()
构造函数仅将句点(&#39;。&#39;)识别为小数点分隔符,但您的输入字符串似乎使用逗号(&#39;,&#39;)那个角色。
如果您无法更正数据以遵循表示十进制数字的现行惯例,那么您需要在样式表中考虑变体约定。您可以使用translate
函数执行此操作。
然而,在你到达那里之前,你的样式表结构中存在严重的问题,其中包括:
你的外xsl:for-each
没有意义。您正在迭代单个(内部)<ROW>
,但您打算处理相应行的对。一个方便的背景是最接近的共同祖先,尽管还有其他方法可以解决这个问题。
您的select
和test
表达式正在尝试引用您要引用属性的子元素。
在某些地方,您的测试是与(不存在的)子元素而不是字符串值进行比较。
总的来说,你已经比它需要的更难。对于您提供的输入,您可能会执行以下操作:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="EVENTS">
<!-- Note @attribute_name syntax for referring to attributes -->
<!-- Note quoted form for string literals -->
<!-- Note that these expressions are evaluated relative to the EVENTS element
matched by this template -->
<!-- Note no iteration: each value wanted is identified via an
appropriate XPath expression -->
<!-- Note use of a select expression to specify the variables' values.
That doesn't make much difference in this particular case, but it
_is_ significant. -->
<xsl:variable name="event_b"
select="ROW[@EVENT_TYPE = 'B']/PRICE/ROW/@EVENT_PRICE"/>
<xsl:variable name="event_p"
select="ROW[@EVENT_TYPE = 'P']/PRICE/ROW/@EVENT_PRICE"/>
<!-- Note use of translate() to translate commas to periods before converting
to numbers -->
<xsl:value-of select="number(translate($event_b, ',', '.')) - number(translate($event_p, ',', '.'))" />
</xsl:template>
</xsl:stylesheet>