这些是我的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>
Run Code Online (Sandbox Code Playgroud)
逻辑是这样的:元素节点应根据节点val和日期排序.First Order必须基于val并且在具有val值的节点序列中.它们应按日期列出.
有谁知道如何通过XPath获取XML节点的排序列表?
有任何想法吗?
您可以使用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>
Run Code Online (Sandbox Code Playgroud)
XPath 3.1 似乎提供了排序功能:
签名
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()*
Run Code Online (Sandbox Code Playgroud)
https://www.w3.org/TR/xpath-functions-31/#func-sort