XSLT 改变元素顺序

标签 xslt

假设我有以下 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>

我想更改顺序,例如先给家人,这样我们就有:

<?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 将模板应用于所有子节点,它还会输出顺序已再次更改的节点,我不知道如何防止它从将模板应用于顺序已更改的节点。

<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,即

<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 更容易编写

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

关于XSLT 改变元素顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37442799/

相关文章:

xslt - XSL 中的求和函数

xml - 从 child 开始计算祖 parent 内的父节点。 XSL

xml - 使用 xpath 和 xslt 选择所有匹配的节点(没有额外的模板或 for-each)

xml - 排序出错

xml - 只获取当前节点的所有文本

xml - 如何在 xslt 中为具有属性的元素不输出空格

c# - 使用 XslCompiledTransform 的正确方法是什么?

xml - XSLT:更改 namespace 的值

html - 参数和变量必须位于模板的顶部吗?

xslt - 覆盖 XSLT 中的命名模板