xml 如何通过 XPath 对值进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4848809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 13:32:22  来源:igfitidea点击:

How to sort values via XPath

xmlxsltxpath

提问by Harold Sota

These is my XML.

这些是我的 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>

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.

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

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

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

Any ideas?

有任何想法吗?

采纳答案by ColinE

You can use xsl:sortto sort matching nodes. This will allow you to sort by your valelement. 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:

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

<?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>

回答by Mostowski Collapse

It seems that XPath 3.1 offers sorting:

XPath 3.1 似乎提供了排序功能:

Signatures

签名

fn:sort($input as item()*) as item()*
fn:sort($input as item()*,  
    $collation as xs:string?) as item()*
fn:sort($input as item()*,  
    $collation as xs:string?,  
    $key as function(item()) as xs:anyAtomicType*) as item()*

https://www.w3.org/TR/xpath-functions-31/#func-sort

https://www.w3.org/TR/xpath-functions-31/#func-sort