如何通过 XPath 对值进行排序 [英] How to sort values via XPath

查看:30
本文介绍了如何通过 XPath 对值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 XML.

<root>

<element>
<title>Title .. </title>
<val>2</val>
<date>21/01/2011</date>
</element>

<element>
<title>Title .. </title>
<val>1</val>
<date>21/01/2011</date>
</element>

<element>
<title>Title .. </title>
<val>2</val>
<date>22/01/2011</date>
</element>

</root>

逻辑是这样的:元素节点应根据节点 val 和 date 进行排名.First Order 必须基于 val 并且在这个具有 val 值的节点序列中.它们应按日期列出.

The logic is this: Element nodes should be ranked according to node val and date. First Order must be based on val and within this sequence of nodes with val value. They should be listed by date.

有谁知道如何通过 XPath 获取 XML 节点的排序列表?

Does anyone know how to get a sorted list of XML nodes via XPath?

有什么想法吗?

推荐答案

您可以使用 xsl:sort 对匹配的节点进行排序.这将允许您按 val 元素进行排序.但是,XPath 1.0 没有日期数据类型.解决此问题的合理解决方案是将日期拆分为年、月和日部分,并按每个部分单独排序.以下应该可以解决问题:

You can use xsl:sort to sort matching nodes. This will allow you to sort by your val element. However, XPath 1.0 does not have a date data-type. A reasonable solution to this problemm is to split your date into its year, month and day components and sort by each individually. The following should do the trick:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="root">
    <xsl:copy>
      <xsl:apply-templates>
        <xsl:sort select="val" data-type="number" order="descending"/>

        <!-- year sort -->
        <xsl:sort select="substring(date,7,4)" data-type="number" />
        <!-- month sort -->
        <xsl:sort select="substring(date,4,2)" data-type="number" />
        <!-- day sort -->
        <xsl:sort select="substring(date,1,2)" data-type="number" />        
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

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

这篇关于如何通过 XPath 对值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆