以与多个选择参数相同的顺序对 XPath 结果进行排序 [英] Sorting XPath results in the same order as multiple select parameters

查看:38
本文介绍了以与多个选择参数相同的顺序对 XPath 结果进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文档,如下所示:

I have an XML document as follows:

<objects>
  <object uid="0" />
  <object uid="1" />
  <object uid="2" />
</objects>

我可以使用以下查询选择多个元素:

I can select multiple elements using the following query:

doc.xpath("//object[@uid=2 or @uid=0 or @uid=1]")

但是这会按照它们在 XML 文档中声明的相同顺序返回元素 (uid=0, uid=1, uid=2) 并且我希望结果的顺序与我执行 XPath 查询的顺序相同 (uid=2, uid=0, uid=1).

But this returns the elements in the same order they're declared in the XML document (uid=0, uid=1, uid=2) and I want the results in the same order as I perform the XPath query (uid=2, uid=0, uid=1).

我不确定单独使用 XPath 是否可行,并研究了 XSLT 排序,但我没有找到解释如何实现这一点的示例.

I'm unsure if this is possible with XPath alone, and have looked into XSLT sorting, but I haven't found an example that explains how I could achieve this.

我正在使用 Ruby 使用 Nokogiri 库.

I'm working in Ruby with the Nokogiri library.

推荐答案

一个 XSLT 示例:

An XSLT example:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:param name="pSequence" select="'2 1'"/>
    <xsl:template match="objects">
        <xsl:for-each select="object[contains(concat(' ',$pSequence,' '),
                                              concat(' ',@uid,' '))]">
            <xsl:sort select="substring-before(concat(' ',$pSequence,' '),
                                               concat(' ',@uid,' '))"/>
            <xsl:copy-of select="."/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

输出:

<object uid="2" /><object uid="1" />

这篇关于以与多个选择参数相同的顺序对 XPath 结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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