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

如何使用XSLT将XML的unitCode元素值转为InvoicedQuantity的属性并删除原元素

实现方案

你可以使用以下XSLT 1.0代码完成转换,核心逻辑基于身份复制模板,仅对需要修改的节点做特殊处理,其余内容原样保留:

<?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>

    <!-- 处理InvoicedQuantity元素,添加unitCode属性 -->
    <xsl:template match="InvoicedQuantity">
        <xsl:copy>
            <!-- 取同级unitCode元素的文本作为属性值 -->
            <xsl:attribute name="unitCode">
                <xsl:value-of select="following-sibling::unitCode[1]/text()"/>
            </xsl:attribute>
            <!-- 复制原InvoicedQuantity的原有属性和内容 -->
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- 匹配unitCode元素,不输出内容即删除该元素 -->
    <xsl:template match="unitCode"/>
</xsl:stylesheet>

逻辑说明

  • 身份转换模板会默认把输入的所有节点、属性原样复制到输出,保证不需要修改的内容和原文件完全一致
  • 匹配InvoicedQuantity的模板会在复制该元素时,新增unitCode属性,取值为它后面第一个同级unitCode元素的文本内容,适配多InvoiceLine节点的场景
  • 最后一个空模板匹配所有unitCode元素,直接跳过输出,实现删除原元素的效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:48:03