XSLT排序使用数字而不是文本

时间:2017-04-07 10:54:22

标签: xml sorting xslt

给出以下XML文件:

<div class="container">
    <div class="row">
        <div class="col-md-3 col-sm-4 col-lg">
           ...
        </div>
        <div class="col-md-3 col-sm-4 col-lg">
           ...
        </div>
        <div class="col-md-3 col-sm-4 col-lg">
           ...
        </div>
        <div class="col-md-3 col-sm-4 col-lg">
           ...
        </div>
        <div class="col-md-3 col-sm-4 col-lg">
           ...
        </div>
        <div class="w-100 hidden-md-down">
               <!--force wrap every 5 on lg-->
        </div>
        <div class="col-md-3 col-sm-4 col-lg">
           ...
        </div>
        <div class="col-md-3 col-sm-4 col-lg">
           ...
        </div>
    </div>
</div>

关注XSLT文件:

<?xml version="1.0"?>
<mappings>
<mapping>
  <class-a>C</class-a>
  <class-b>a</class-b>
</mapping>
<mapping>
  <class-a>B</class-a>
  <class-b>b</class-b>
</mapping>
<mapping>
  <class-a>A</class-a>
  <class-b>c</class-b>
</mapping>
</mappings>

产生这个错误的XML结果:

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

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="mappings">
  <xsl:copy>
    <xsl:apply-templates>
          <xsl:sort select="(name() = 'mapping')*class-a" data-type="text" order="ascending" />
    </xsl:apply-templates>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

预期结果是:

<?xml version="1.0" encoding="UTF-8"?>
<mappings>
   <mapping>
      <class-a>C</class-a>
      <class-b>a</class-b>
   </mapping>
   <mapping>
      <class-a>B</class-a>
      <class-b>b</class-b>
   </mapping>
   <mapping>
      <class-a>A</class-a>
      <class-b>c</class-b>
   </mapping>
</mappings>

映射应根据<?xml version="1.0" encoding="UTF-8"?> <mappings> <mapping> <class-a>A</class-a> <class-b>c</class-b> </mapping> <mapping> <class-a>B</class-a> <class-b>b</class-b> </mapping> <mapping> <class-a>C</class-a> <class-b>a</class-b> </mapping> </mappings> 元素值按字母顺序排序。

通过在输入XML的class-a元素中使用数字代替字符串:

class-a

在XSLT排序标记中使用<?xml version="1.0"?> <mappings> <mapping> <class-a>3</class-a> <class-b>a</class-b> </mapping> <mapping> <class-a>2</class-a> <class-b>b</class-b> </mapping> <mapping> <class-a>1</class-a> <class-b>c</class-b> </mapping> </mappings> data-type="text",我们得到了相同的预期结果:

data-type="number"

是否有人知道如何通过文字获得预期结果?

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

        <xsl:sort select="class-a" data-type="text" order="ascending"  />

答案 1 :(得分:1)

我终于想出了如何获得预期结果:

<xsl:sort select="class-a[name(..) = 'mapping']" data-type="text" />

@Tomalak:谢谢你,你让我走上正轨!

@Rupesh:您的解决方案适用于简单案例(包括给定示例)但如果<mapping>中还有其他类型的元素,则不允许仅对<mappings>个元素进行排序标签有自己的<class-a>子元素......