【问题标题】:passing parameter variable XSLT 1.0传递参数变量 XSLT 1.0
【发布时间】:2015-04-19 16:20:26
【问题描述】:

我有类似以下 XML 的东西:(但有更多产品)

<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <name>Mango</name>
        <type>fruit</type>
        <imageurl>pic.jpeg</imageurl>
    </product>
    <product>
        <name>banana</name>
        <type>fruit</type>
        <imageurl>pic3.jpeg</imageurl>
    </product>
    <product>
        <name>duck</name>
        <type>mammal</type>
        <imageurl>pic2.jpeg</imageurl>
    </product>
</products>

还有这个 XSL:(但有更多的元素和属性)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:param name="typeSelected"/>
<xsl:template match="product/{$typeSelected}">
    <xsl:element name="img">
        <xsl:attribute name="class">juice</xsl:attribute>
        <xsl:attribute name="src">
            <xsl:value-of select="imageurl"/>
        </xsl:attribute>
    </xsl:element>
</div>
</xsl:template>

我正在使用外部 JavaScript 文件设置参数的值,但我想只对 &lt;type&gt; 匹配该参数值的产品进行分组。显然,XSL 需要更改并且已经阅读了我知道我不能在 match 语句中使用参数。感觉我尝试的东西不应该太难。我错过了什么明显的东西吗?

给定参数fruit,我希望输出类似于:

<img class="juice" src="pic.jpeg"/>
<img class="juice" src="pic3.jpeg"/>

【问题讨论】:

    标签: xml xslt xslt-1.0


    【解决方案1】:

    我会这样做:

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
    
    <xsl:param name="typeSelected"/>
    
    <xsl:key name="product-by-type" match="product" use="type" />
    
    <xsl:template match="/">
        <root>
            <xsl:for-each select="key('product-by-type', $typeSelected)">
                <img class="juice" src="{imageurl}"/>
            </xsl:for-each>
        </root>
    </xsl:template>
    
    </xsl:stylesheet>
    

    结果(当 $typeSelected = "fruit" 时):

    <?xml version="1.0" encoding="utf-8"?>
    <root>
       <img class="juice" src="pic.jpeg"/>
       <img class="juice" src="pic3.jpeg"/>
    </root>
    

    注意

    1. XML 文档必须有根元素;

    2. class 属性的内容是硬编码的;我在您的输入中没有看到它;

    3. 鸭子不是哺乳动物。

    【讨论】:

    • 谢谢鸭子,效果很好。如果您想查看您帮助创建的业余页面here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2011-12-23
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    相关资源
    最近更新 更多