XSLT技术求助:如何将父节点serialShippingContainerCode值复制到子节点?
问题解决:XSLT传递父节点值到子节点新标签
原代码问题分析
- 重复模板冲突:定义了两个匹配
LogisticUnitLineItem的模板,仅最后一个生效,且第一个模板丢弃了原节点的logisticUnitIdentification内容。 - 路径错误:
/serialShippingContainerCode是绝对路径,无法定位到当前LogisticUnitLineItem下的目标节点,需要使用相对路径。 - 节点位置错误:新的
<Identification>标签应添加到每个containedItemIdentification末尾,而非直接放在LogisticUnitLineItem节点下。
修正后的XSLT代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.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> <!-- 匹配containedItemIdentification,添加新的Identification节点 --> <xsl:template match="containedItemIdentification"> <xsl:copy> <!-- 复制原有内容 --> <xsl:apply-templates select="@* | node()"/> <!-- 添加新的Identification节点 --> <Identification> <IdentificationValue> <!-- 从当前节点的祖先LogisticUnitLineItem中获取serialShippingContainerCode的值 --> <xsl:value-of select="ancestor::LogisticUnitLineItem/logisticUnitIdentification/ContainerCode/serialShippingContainerCode"/> </IdentificationValue> <IdentificationType>PAL</IdentificationType> </Identification> </xsl:copy> </xsl:template> </xsl:stylesheet>
关键说明
- 身份转换模板:保留原有XML结构的所有内容,确保除了需要修改的部分外,其他节点原样输出。
- 定位目标值:使用
ancestor::LogisticUnitLineItem向上查找当前containedItemIdentification所属的父级LogisticUnitLineItem,再通过相对路径定位到serialShippingContainerCode节点,获取其文本值。 - 添加新节点:在
containedItemIdentification的原有内容之后,插入包含容器编码的新<Identification>节点,符合期望输出的结构。
内容的提问来源于stack exchange,提问作者CHAR
相关产品推荐
相关产品推荐

