如何使用XSLT 3.0为<item>动态加子元素并转换<constant>属性?
XSLT实现指定XML转换方案指导
需求概述
- 主元素
<root>下的<item>需要从<extraData>下的<constant>元素获取信息:- 当
<constant>的code属性为"code01"时,将其<value>内容作为<item>的新子元素<newTag>
- 当
- 处理
<extraData>下的<constant>元素:- 移除
code属性为"code01"的<constant>元素 - 对
code属性为其他值的<constant>,将code属性转换为带__前缀的子元素<__code>,同时移除原code属性
- 移除
示例输入XML
<root> <item> <ref>Initial Value</ref> </item> <extraData> <constant code="code01"> <value>New Value</value> <othertags>Random thing</othertags> </constant> <constant code="code02"> <value>New Value 2</value> <othertags>Random thing 2</othertags> </constant> </extraData> </root>
期望转换结果
<root> <item> <ref>Initial Value</ref> <newTag>New Value</newTag> </item> <extraData> <constant> <__code>code02</__code> <value>New Value 2</value> <othertags>Random thing 2</othertags> </constant> </extraData> </root>
实现XSLT代码
<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> <!-- 处理<item>节点:添加newTag --> <xsl:template match="item"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <!-- 提取code为code01的constant下的value内容,创建newTag --> <newTag> <xsl:value-of select="/root/extraData/constant[@code='code01']/value"/> </newTag> </xsl:copy> </xsl:template> <!-- 移除code为code01的constant节点 --> <xsl:template match="constant[@code='code01']"/> <!-- 处理code属性不为code01的constant节点 --> <xsl:template match="constant[@code!='code01']"> <xsl:copy> <!-- 将code属性转换为__code子元素 --> <__code> <xsl:value-of select="@code"/> </__code> <!-- 复制constant下的所有子节点,跳过原code属性 --> <xsl:apply-templates select="node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
代码解释
- 身份模板:作为基础逻辑,默认复制XML中所有未被其他模板匹配的节点和属性,保证原有结构大部分保留。
- 处理模板
:匹配<item>节点,在复制原有内容后,通过XPath定位到code="code01"的<constant>下的<value>,创建<newTag>并填充对应内容。- 移除指定constant模板:匹配
code="code01"的<constant>节点,不做任何输出,直接移除该节点。 - 处理其他constant模板:匹配
code不为code01的<constant>,复制节点本身后,将原code属性值转为<__code>子元素,再复制该节点下的所有子节点。
内容的提问来源于stack exchange,提问作者zerotsu
相关产品推荐
相关产品推荐

