代码之家  ›  专栏  ›  技术社区  ›  Amit Panasara

用于根据元素的属性对特定XML标记的元素进行排序的XSLT

  •  -1
  • Amit Panasara  · 技术社区  · 6 年前

    要转换(排序)“特定标记的元素”

    我刚接触XSLT。因此需要了解XSLT如何处理特定的标记。

    当前XML

    <root>
        <tag>bla bla bla</tag>
        <tag>foo foo foo</tag>
        <tag>
             <particular-tag>
                   <element attrib="2"/>
                   <element attrib="3"/>
                   <element attrib="4"/>
                   <element attrib="1"/>
             </particular-tag>
             <particular-tag>
                   <element attrib="5"/>
                   <element attrib="3"/>
                   <element attrib="4"/>
             </particular-tag>
        </tag>
    </root>
    

    期望的XML

    <root>
        <tag>bla bla bla</tag>
        <tag>foo foo foo</tag>
        <tag>
             <particular-tag>
                   <element attrib="1"/>
                   <element attrib="2"/>
                   <element attrib="3"/>
                   <element attrib="4"/>
             </particular-tag>
             <particular-tag>
                   <element attrib="3"/>
                   <element attrib="4"/>
                   <element attrib="5"/>
             </particular-tag>
        </tag>
    </root>
    

    事先谢谢。您可以建议我使用XML-XLST的在线学习源代码。

    2 回复  |  直到 6 年前
        1
  •  -1
  •   Kirill Polishchuk    6 年前

    此XSLT将产生所需的结果:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="particular-tag">
        <xsl:copy>
          <xsl:apply-templates select="*">
            <xsl:sort select="@attrib"/>
          </xsl:apply-templates>
        </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>
    
        2
  •  -1
  •   Mister Lucky    6 年前

    这会产生你想要的结果。 希望它有帮助。

    <?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" encoding="utf-8"/>
    
      <xsl:template match="particular-tag">
        <particular-tag>
          <xsl:apply-templates select="element">
            <xsl:sort select="@attrib"/>
          </xsl:apply-templates>
        </particular-tag>
      </xsl:template>
    
      <xsl:template match="@*|node()">
        <xsl:choose>
          <xsl:when test="node()">
            <xsl:copy>
              <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
          </xsl:when>
          <xsl:otherwise>
            <xsl:copy>
              <xsl:apply-templates select="@*"/>
            </xsl:copy>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:template>
    
    </xsl:stylesheet>