根据XSL中的另一个元素获取元素值

时间:2013-11-19 23:18:28

标签: xml xslt xslt-2.0

我需要根据之前检索的价格检索供应商代码

价格是这样检索的

<xsl:template match="Price">
    <xsl:if test="position() = 1">
        <xsl:value-of select="."/>
    </xsl:if>
</xsl:template>

<xsl:apply-templates select="current-group()/Price">
    <xsl:sort select="." data-type="text" order="ascending"/>
</xsl:apply-templates>

我能做些什么来获得该价格的供应商代码

<xsl:variable name="SupplierCode" select="current-group()/SupplierCode"/>

XML示例

<Search-Request search-term="1 tb">
    <Items>
        <Item href="SEA1TBST31000524AS.jpg" model="ST31000524AS">
            <Name>Seagate Hard disk 1TB ST31000524AS 3.5"</Name>
            <Price>60.50</Price>
            <SupplierCode>TECSEA1TB</SupplierCode>
            <Supplier>TEC001</Supplier>
            <Manufacturer>Seagate</Manufacturer>
        </Item>
        <Item href="" model="ST31000524AS">
            <Name>Seagate Hard disk 1TB ST31000524AS 3.5 inch</Name>
            <Price>55.50</Price>
            <SupplierCode>SCASEA1TB</SupplierCode>
            <Supplier>SCA001</Supplier>
            <Manufacturer>Seagate</Manufacturer>
        </Item>
     </Items>
 </Search-Request>

我也按以下方式分组。

<xsl:for-each-group select="Items/Item" group-by="@model">

1 个答案:

答案 0 :(得分:0)

对于每个“模型”,您正试图为该模型找到最便宜的物品。

要获取当前 Price 元素的 SupplierCode ,您可以这样做......

<xsl:template match="Price">
    <xsl:if test="position() = 1">
        <xsl:value-of select="."/>
        <xsl:value-of select="../SupplierCode" />
    </xsl:if>
</xsl:template>

其中..用于获取当前节点的父节点。

或者,你可以做的不是选择价格元素,而是选择商品元素,按价格 <排序/ p>

<xsl:apply-templates select="current-group()">
    <xsl:sort select="Price" data-type="number" order="ascending"/>
</xsl:apply-templates>

然后,您可以拥有与元素匹配的模板,在此您可以轻松访问价格代码 < / p>

<xsl:template match="Item">
    <xsl:if test="position() = 1">
        <xsl:value-of select="Price" />
        <xsl:value-of select="Code" />
    </xsl:if>
</xsl:template>
编辑:在回答您的评论时,如果您只想要具有最低价格的项目的SupplierCode,您将更改与项目元素匹配的模板以仅输出供应商代码,然后将 xsl:apply-templates 包装在变量中。

试试这个XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" />

<xsl:template match="/*">
   <xsl:for-each-group select="Items/Item" group-by="@model">
      <xsl:variable name="SupplierCode">
         <xsl:apply-templates select="current-group()">
            <xsl:sort select="Price" data-type="number" order="ascending"/>
         </xsl:apply-templates>
      </xsl:variable>
      <xsl:value-of select="$SupplierCode" />
   </xsl:for-each-group>
</xsl:template>

<xsl:template match="Item">
    <xsl:if test="position() = 1">
        <xsl:value-of select="SupplierCode"/>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

实际上,还有另一种方法可以做到这一点。您可以在XSLT 2.0中使用 min 运算符

   <xsl:value-of select="current-group()[number(Price)=min(current-group()/Price)]/SupplierCode" />

这不一定像以前的方法一样有效,因为你有效地检查了两次“current-group()”。首先获得最小值,然后再次找到当前组中具有最低价格的项目。

相关问题