2017-06-19 104 views
1

我在这个例子中的文件有问题,减去:减去XSLT 1.0

<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> 

我必须减去从P型event_price对应一个类型B.在这个例子中,我想得到一个结果40,并将其输出到结果树中,但它不起作用。怎么了?

+0

发布你的代码,所以我们不必猜测你的问题是什么。 - 提示:为了将价格识别为数字,您需要将逗号转换为点。 –

+0

请不要在评论中张贴代码 - 而是编辑您的问题。还要确保你的代码是**完整的** - 见:[mcve]。 –

+0

我需要这个165,00-125,00 = 40,00的结果。我的数字格式没有问题。我在显示一个名为event_price_subtract的节点中减去一个结果的问题。 – jeffers

回答

0

您正在尝试将字符串转换为数字,但这些字符串未针对XSL/XPath/XSI编号正确格式化。具体而言,number()构造函数只将句点('。')字符识别为小数分隔符,但输入字符串似乎在该角色中使用逗号(',')。

如果您无法更正数据以遵循主流约定来表示十进制数,那么您需要在样式表中考虑变体约定。您可以使用translate函数执行此操作。

甚至在你到达那里,但是,你有严重的问题,在样式表结构,其中:

  • 您的外xsl:for-each没有意义。您正在遍历单个(内部)<ROW>,但您打算处理对应行的。一个方便的背景将是最接近的共同祖先,尽管还有其他方法来解决这个问题。

  • 您的selecttest表达式正试图引用子元素,您的意思是指引用属性。

  • 在某些地方,您的测试正在比较(不存在的)子元素而不是字符串值。

总的来说,你做得比它需要的要难得多。对于你提出的输入,你可能会这样做:

<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>