2013-10-23 43 views
0

我仍在努力让自己的头部围绕许多XSLT,但有一个具体问题。通过简单嵌套结构上的属性对元素进行排序

我有一个简单的嵌套结构,我想按属性(名称)排序。

该文件具有单个根节点,然后是一系列嵌套节点。我需要将根目录下的所有节点按照它们的级别进行排序。层次结构嵌套到未指定的级别。

输入:

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <node name="A"> 
    <node name="C"/> 
    <node name="B"/> 
    </node> 
    <node name="F"/> 
    <node name="E"/> 
</root> 

需要转换成:

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <node name="A"> 
    <node name="B"/> 
    <node name="C"/> 
    </node> 
    <node name="E"/> 
    <node name="F"/> 
</root> 

我不会和我在解决这个feable尝试来烦你。

回答

0

假设你想要的元素留他们目前的水平内,首先,你需要一个模板来匹配任何元素

<xsl:template match="*"> 

那么你可以使用XSL:复制复制元素,XSL:复制的复制任何属性

<xsl:copy> 
    <xsl:copy-of select="@*"/> 
    ... more code here... 
    </xsl:copy> 

而且XSL中:复制你会再使用XSL:申请模板处理子元素,与XSL一起:排序选择顺序

 <xsl:apply-templates select="*"> 
     <xsl:sort select="@name" /> 
    </xsl:apply-templates> 

将这个完全给你这个

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output omit-xml-declaration="yes" indent="yes" /> 
    <xsl:template match="*"> 
     <xsl:copy> 
     <xsl:copy-of select="@*"/> 
     <xsl:apply-templates select="*"> 
      <xsl:sort select="@name" /> 
     </xsl:apply-templates> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

当适用于您的输入XML以下是输出

<root> 
    <node name="A"> 
    <node name="B"/> 
    <node name="C"/> 
    </node> 
    <node name="E"/> 
    <node name="F"/> 
</root> 
0

这个答案类似于蒂姆C的,但只是使用一个标识ty转换为xsl:sort。这样,如果他们在场,您不会丢失评论或处理说明。

XSLT 1.0

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

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

</xsl:stylesheet> 
相关问题