使用 XSLT 对 XML 中的节点进行排序 [英] Sort nodes in XML using XSLT

查看:37
本文介绍了使用 XSLT 对 XML 中的节点进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XSL 变量 matchedNodes 保存 XML 数据.这意味着

I have an XSL variable matchedNodes which holds XML data. Which means

   <xsl:copy-of select="$matchedNodes"/>

将产生这样的 XML

    <home name="f">
  <standardpage>
    <id text="a1"></id>
  </standardpage>
  <searfchpage>
    <id text="a2"></id>
  </searfchpage>
  <searfchpage>
    <id text="a3"></id>
  </searfchpage>
</home>

我想对这个 XML 进行排序,以便 searfchpage 节点总是排在最前面..有什么办法可以做到这一点?

I want to sort this XML so that searfchpage nodes always comes first..Is there any way to do this?

推荐答案

简单排序(将 移到顶部,其余子项保持原始顺序):

Simple ordering (move <searfchpage> to the top, keep the rest of the children in orignal order):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

  <xsl:template match="home">
    <xsl:copy>
      <xsl:apply-templates select="@*" />
      <xsl:apply-templates select="searfchpage" />
      <xsl:apply-templates select="*[not(self::searfchpage)]" />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

复杂排序(允许您定义任意顺序,可以通过参数动态定义,也可以通过硬编码字符串静态定义):

complex ordering (lets you define any arbitrary order, either dynamically via a param or statically via a hard-coded string):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="sortOrder" select="'searfchpage,standardpage,otherpage'" />

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

  <xsl:template match="home">
    <xsl:copy>
      <xsl:apply-templates select="@*">
      <xsl:apply-templates select="*">
        <xsl:sort select="string-length(
          substring-before(concat($sortOrder, ',', name()), name())
        )" />
      <xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

这篇关于使用 XSLT 对 XML 中的节点进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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