You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用XSLT 1.0为多个空白XML元素设置默认值

用XSLT 1.0为空白XML元素设置默认值

输入XML

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

期望输出XML

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

实现的XSLT代码

<?xml version="1.0" encoding="UTF-8"?>
<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(node())]">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:text>default</xsl:text>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

关键说明

  1. 身份模板:作为基础规则,负责复制XML中所有原本的节点、属性和文本,确保非空白元素保持原样。
  2. 空白元素匹配模板:通过*[not(node())]定位没有任何子节点(包括文本、子元素)的元素,这类元素就是需要填充默认值的目标。模板会复制元素本身及所有属性,再插入指定的默认文本。

扩展:处理含空白字符的空元素

如果需要处理<name> </name>这类包含空白字符的空元素,可以将匹配条件改为*[normalize-space() = ''],修改后的模板如下:

<xsl:template match="*[normalize-space() = '']">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:text>default</xsl:text>
    </xsl:copy>
</xsl:template>

normalize-space()会去除文本前后空白并合并中间连续空白,结果为空字符串即判定为需要处理的空元素。

内容的提问来源于stack exchange,提问作者Anirban

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 14:41:04