在XSL中使用xml查询设置if条件

时间:2014-05-23 18:43:42

标签: xml xslt xslt-1.0

大家好,我们想知道是否有人可以协助我使用XSL进行逻辑实现我遇到了问题。

我正在查询返回5个Microsoft产品和2个Apple产品的xml文件。我想要做的是显示所有的微软产品,具体取决于发现了多少苹果产品。

因此,如果只找到一种苹果产品。然后它应该抓住4个微软产品,但如果发现2个苹果产品,它应该抓住3个微软产品展示。

到目前为止

我的XSL

<xsl:call-template name="WRITEPRODUCTSET">
<xsl:with-param name="PRODUCTS" select="/Result/records[ @name = 'microsoft' ]" />
</xsl:call-template>
<xsl:call-template name="WRITEPRODUCTSET">
<xsl:with-param name="PRODUCTS" select="/Result/records[ @name != 'apple' ]" />
</xsl:call-template>

感谢您阅读,我们将非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以将数据存储在变量中,然后在计算中使用它们:

<xsl:variable name="apple-products"     select="//records[@name='apple']"/>
<xsl:variable name="microsoft-products" select="//records[@name='microsoft']"/>

例如:

<xsl:variable name="ms-products-to-return" 
       select="count($microsoft-products) - count($apple-products)"/> 

然后,您可以使用谓词来限制集合,以决定应该返回哪些产品。例如,此样式表将按文档顺序返回它们:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:variable name="apple-products"     select="//records[@name='apple']"/>
    <xsl:variable name="microsoft-products" select="//records[@name='microsoft']"/>

    <xsl:template match="Result">
       <xsl:variable name="ms-products-to-return" 
           select="count($microsoft-products) - count($apple-products)"/> 
        <xsl:apply-templates 
             select="$microsoft-products[position() &lt;= $ms-products-to-return]" />
    </xsl:template>

    <xsl:template match="records">
        <xsl:copy-of select="."/>
    </xsl:template>

</xsl:stylesheet>