如何使用xsl对一行中的节点组进行排序?

时间:2012-02-17 23:27:00

标签: xml xslt xpath

下面是我的xml

<products>
    <product>
        <item>Pen</item>
        <price>10</price>
    </product>
    <product>
        <item>Pencil</item>
        <price>20</price>
    </product>
    <product>
        <item>Bag</item>
        <price>25</price>
    </product>
</products>

我需要输出如下

product_name       price     remark
Pen                10        Pen+Pencil+Bag
Pencil             20        Pen+Pencil+Bag
Bag                25        Pen+Pencil+Bag

我如何在{xllt 1.0

中作为组remark

1 个答案:

答案 0 :(得分:0)

此转化

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

 <xsl:variable name="vSortedNames">
  <xsl:call-template name="sortedItemList"/>
 </xsl:variable>

 <xsl:template match="/*">
  <xsl:text>product_name&#9;price&#9;remark</xsl:text>

  <xsl:apply-templates select="*">
   <xsl:sort select="price" data-type="number"/>
  </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="product">
  <xsl:value-of select=
  "concat('&#xA;', item, '&#9;', price, '&#9;', $vSortedNames)"/>
 </xsl:template>

 <xsl:template name="sortedItemList">
  <xsl:for-each select="/*/product">
   <xsl:sort select="price" data-type="number"/>
  <xsl:if test="not(position() = 1)">+</xsl:if>
   <xsl:value-of select="item"/>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<products>
    <product>
        <item>Pen</item>
        <price>10</price>
    </product>
    <product>
        <item>Pencil</item>
        <price>20</price>
    </product>
    <product>
        <item>Bag</item>
        <price>25</price>
    </product>
</products>

生成想要的正确结果

product_name    price   remark
Pen 10  Pen+Pencil+Bag
Pencil  20  Pen+Pencil+Bag
Bag 25  Pen+Pencil+Bag