简体   繁体   English

XML文件使用XSLT对特定节点进行排序

[英]XML file sort particular nodes using XSLT

I am not very good with xsl, but I would like to sort the following xml: 我对xsl不太满意,但我想对以下xml进行排序:

<Parent>
        <node1/>
        <class>b</class>

        <class>c</class>


         <node2/> 
        <class>a</class>
</Parent>

into the following so that only the class elements are sorted and other elements are untouched: 分为以下几类,以便仅对class元素进行排序,而其他元素保持不变:

<Parent>
        <node1/>
        <class>a</class>
        <class>b</class>
        <class>c</class>
        <node2/>        
</Parent>

I am using the following xsl within a java code to transform my xml : 我在Java代码中使用以下xsl转换我的xml:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
     <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template> 
  <xsl:template match="class">
    <xsl:copy>
    <xsl:apply-templates select="*" >
    <xsl:sort order="ascending" select="class" />

    </xsl:apply-templates>
    </xsl:copy>
    </xsl:template> 
</xsl:stylesheet>

this gives me : 这给了我:

<Parent>
    <node1/>
    <class/>
    <class/>
    <node2/>
    <class/>
</Parent>

Use: 采用:

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

  <xsl:template match="class[1]">
    <xsl:for-each select="//class">
      <xsl:sort select="."/>
      <xsl:copy-of select="."/>
    </xsl:for-each>
  </xsl:template>

  <xsl:template match="class"/>

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

</xsl:stylesheet>

Output: 输出:

<Parent>
  <node1 />
  <class>a</class>
  <class>b</class>
  <class>c</class>
  <node2 />
</Parent>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM