XSLT 更改元素顺序 [英] XSLT Change element order

查看:28
本文介绍了XSLT 更改元素顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 xml:

Say I have the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns="http://someorg.org">
    <name>
    <use value="usual"/>
    <family value="family"/>
    <given value="given"/>
    <suffix value="MSc"/>
  </name>
</Test>

我想更改顺序,例如在家人之前给出,以便我们:

and I would like to change the order by for example having given before family so that we have:

<?xml version="1.0" encoding="UTF-8"?>
<Test xmlns="http://someorg.org">
    <name>
    <use value="usual"/>
    <given value="given"/>
    <family value="family"/>    
    <suffix value="MSc"/>
  </name>
</Test>

我尝试使用 xsl:paply.template 如下,但问题是由于 apply-templates 将模板应用于所有子节点,它还会输出顺序已再次更改的节点,我不知道如何防止它将模板应用于已更改顺序的节点.

I tried using xsl:paply.template as below but the problem is that since apply-templates applies templates to all child nodes, it would also output nodes whose order has being changed again and I do not know how I can prevent it from applying templates to nodes whose order has already being changed.

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://someorg.org"
xmlns="http://someorg.org"
exclude-result-prefixes="f xsl">

    <xsl:template match="*">
        <xsl:element name="{local-name(.)}">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
    </xsl:template>


    <xsl:template match="@*">
        <xsl:attribute name="{local-name(.)}">
            <xsl:value-of select="."/>
        </xsl:attribute>
    </xsl:template>

    <xsl:template match="/">

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

    <xsl:template match = "f:name">
    <xsl:apply-templates select = "f:given"/>
    <xsl:apply-templates select = "f:family"/>
    <xsl:apply-templates/>          
    </xsl:template>     
</xsl:stylesheet>

推荐答案

要更改顺序,您需要将 apply-templates 设置为您想要的顺序,即

To change the order you need to have the apply-templates in the order you want, i.e.

<xsl:template match = "f:name">
  <xsl:copy>
     <xsl:apply-templates select="f:use"/>
     <xsl:apply-templates select="f:given"/>
     <xsl:apply-templates select="f:family"/>
     <xsl:apply-templates select="f:suffix"/>
  </xsl:copy>          
</xsl:template>    

使用 XSLT 2.0 更容易编写

With XSLT 2.0 it is easier to write

<xsl:template match = "f:name">
  <xsl:copy>
     <xsl:apply-templates select="f:use, f:given, f:family, f:suffix"/>
  </xsl:copy>          
</xsl:template>  

这篇关于XSLT 更改元素顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆