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

XML处理:如何将空ContentVersion元素替换为预设Dummy元素?

用XSLT替换XML中空的ContentVersion元素

问题分析

你的XML文档带有命名空间http://www.xml.com/20040511#,这是之前XSLT转换失败的常见原因——没有正确处理命名空间。我们需要在XSLT中声明该命名空间,并以此匹配目标元素。

完整XSLT代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:ns="http://www.xml.com/20040511#"
                exclude-result-prefixes="ns">

    <!-- 身份转换模板:默认复制所有节点和属性 -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- 匹配空的ContentVersion元素:无Id子元素,且LabelText为空 -->
    <xsl:template match="ns:ContentVersion[not(ns:Id) and ns:LabelText/text()='']">
        <ns:ContentVersion>
            <ns:Id>urn:uuid:11111111-1111-1111-1111-111111111111</ns:Id>
            <ns:LabelText>DUMMY</ns:LabelText>
        </ns:ContentVersion>
    </xsl:template>

    <!-- 处理ContentVersion包含自闭合空LabelText的场景 -->
    <xsl:template match="ns:ContentVersion[not(ns:Id) and ns:LabelText[not(text())]]">
        <ns:ContentVersion>
            <ns:Id>urn:uuid:11111111-1111-1111-1111-111111111111</ns:Id>
            <ns:LabelText>DUMMY</ns:LabelText>
        </ns:ContentVersion>
    </xsl:template>

</xsl:stylesheet>

代码说明

  1. 命名空间绑定:通过xmlns:ns="http://www.xml.com/20040511#"将原XML的命名空间绑定到前缀ns,后续匹配元素时必须使用该前缀,否则无法定位目标节点。
  2. 身份转换模板:确保XML中所有未被特殊匹配的元素、属性和文本都被原样复制,只修改符合条件的ContentVersion元素。
  3. 双匹配条件:覆盖两种空状态场景——LabelText为空文本,或是自闭合的空标签,确保所有符合你描述的空ContentVersion都能被替换。

转换效果

对于输入的空ContentVersion:

<ContentVersion>
    <LabelText/>
</ContentVersion>

会被替换为预设的Dummy内容:

<ContentVersion>
    <Id>urn:uuid:11111111-1111-1111-1111-111111111111</Id>
    <LabelText>DUMMY</LabelText>
</ContentVersion>

正常的ContentVersion元素则会被原样保留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:52:03