使用 XSLT 1.0 在多个 XML 元素中应用默认值

问题描述 投票:0回答:1

我正在使用 XSLT 1.0。需要使用 XSLT 对所有空白 XML 元素应用默认值。例如,下面是输入 XML:

<employee>
    <id attributeName="attributeValue">1111</id>
    <name attributeName="attributeValue" />
    <address attributeName="attributeValue" />
</employee>

此处 XML 元素名称和地址的值为空。我需要用默认值填充这些值,以便 XML 如下所示:

<employee>
    <id attributeName="attributeValue">1111</id>
    <name attributeName="attributeValue">default</name>
    <address attributeName="attributeValue">default</address>
</employee>

有人可以建议我如何使用 XSLT 1.0 来做到这一点吗?抱歉,如果这个问题很幼稚,因为我不是 XSLT 方面的专家。

xml xpath xslt-1.0
1个回答
0
投票

修改没有任何子节点(包括文本)的节点就足够了:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

    <xsl:template match="*[not(*)]">
        <xsl:copy>
            <xsl:copy-of select="@*" />
            <xsl:text>default</xsl:text>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
<employee>
    <id attributeName="attributeValue">1111</id>
    <name attributeName="attributeValue">default</name>
    <address attributeName="attributeValue">default</address>
</employee>
© www.soinside.com 2019 - 2024. All rights reserved.