使用XSLT转换器将XML排序为XML

时间:2016-06-29 06:55:58

标签: xml xslt

我有像这样的xml

<?xml version="1.0" encoding="UTF-8"?> 
<MANAGER_HIERARCHY> 
  <tables>
    <II_OUTPUT>
      <row id="0">
        <LNAME>Gola</LNAME> 
      </row> 
      <row id="1">
        <LNAME>Chaganti</LNAME>
      </row>
    </II_OUTPUT>
  </tables>
</MANAGER_HIERARCHY>

我想基于LNAME对xml进行排序,我期待以下输出

<?xml version="1.0" encoding="UTF-8"?>
<MANAGER_HIERARCHY>
  <tables>
    <II_OUTPUT>
      <row id="0">
        <LNAME>Chaganti</LNAME>
      </row>
      <row id="1">
       <LNAME>Gola</LNAME>
      </row>
    </II_OUTPUT>
  </tables>
</MANAGER_HIERARCHY>

我已经编写了一个XSLT来做同样的事情但是我无法排序。请建议我编写XSLT代码来实现我的要求。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns="urn:Test.Namespace">
  <xsl:output indent="yes" />
  <xsl:strip-space elements="*"/>

  <xsl:template match="text()[not(string-length(normalize-space()))]"/>

  <xsl:template match="/">
    <xsl:apply-templates/>
    <xsl:apply-templates select="MANAGER_HIERARCHY/tables/row">
      <xsl:sort select="*/LNAME" />
    </xsl:apply-templates>
  </xsl:template>

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

1 个答案:

答案 0 :(得分:1)

您正在尝试对row元素进行排序,这些元素是II_OUTPUT的子节点。这意味着您只需要一个匹配II_OUTPUT的模板,然后在其中复制它,然后按照您需要的顺序选择子row元素。

<xsl:template match="II_OUTPUT">
  <xsl:copy>
    <xsl:apply-templates select="row">
      <xsl:sort select="LNAME" />
    </xsl:apply-templates>
  </xsl:copy>
</xsl:template>

您已包含的身份模板将处理其他所有内容。

试试这个XSLT

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

  <xsl:template match="text()[not(string-length(normalize-space()))]"/>

  <xsl:template match="II_OUTPUT">
    <xsl:copy>
      <xsl:apply-templates select="row">
        <xsl:sort select="LNAME" />
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

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