使用 XSLT 将嵌套代码从 xml 合并到 xml



我有一个问题。
我有第一个xml:

<?xml version = '1.0' encoding = 'UTF-8'?>
<groups>
<group>
<number>1</number>
</group>
<group>
<number>2</number>
</group>
<group>
<number>3</number>
</group>
</groups>

使用 XSLT,我希望它像:

<?xml version = '1.0' encoding = 'UTF-8'?>
<groups>
<group number="1"/>
<group number="2"/>
<group number="3"/>
</groups>

我现在使用的 xslt 样式表是:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*"/>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="groups">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="number">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

但它只删除"组"字段。需要帮助!
提前致谢

您可以从标识转换开始,因为输入和输出中的节点名称和结构非常接近。这会按原样将输入 XML 复制到输出。

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

下一步是<number>节点转换为<group>节点的属性。因此,将创建一个模板来匹配group/number节点。

<xsl:template match="group/number">

在此模板中,如注释中所述,需要定义<xsl:attribute>。在这种情况下,由于属性名称与当前节点名称匹配,因此使用{}中的local-name()。属性的值是当前<number>节点的值。

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

下面是将输入 XML 转换为所需输出的完整 XSLT。

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:strip-space elements="*" />
<xsl:output method="xml" indent="yes" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="group/number">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="." />
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>

输出

<groups>
<group number="1" />
<group number="2" />
<group number="3" />
</groups>

最新更新