gpt4 book ai didi

XSLT 改变元素顺序

转载 作者:行者123 更新时间:2023-12-02 09:26:33 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com