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