且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

XSLT 排序 - 如何使用属性对父节点内的 xml 子节点进行排序

更新时间:2023-02-03 12:33:04

所以你是说你只是将 XML 文档的一部分(一个 节点)传递给 XSLT处理器?

So are you saying that you're only passing part of your XML document (one <year> node) to the XSLT processor?

您应该为年份使用单独的模板,以便这是唯一使用排序的模板.以下如何:

You should use a separate template for year, so that that's the only template that uses sorting. How is the following:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>
  <xsl:strip-space elements="*"/>

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

  <xsl:template match="year">
    <xsl:copy>
      <xsl:apply-templates select="@*" />
      <xsl:apply-templates select="post">
        <xsl:sort select="@postid" data-type="number" order="descending"/>
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

我认为以上是一个更好的方法,但我认为您的错误的根本原因是它在进行排序时将属性与元素混合在一起.如果您只是这样做,您的原始 XSLT 可能会运行而不会出错:

I think the above is a better approach, but I think the root cause of your error is that it was mingling the attributes in with the elements when it did the sorting. Your original XSLT probably would run without error if you simply did this:

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*">
        <xsl:apply-templates select="node()">
            <xsl:sort select="@postid" data-type="text" order="descending"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>