编写XSLT映射合并同类节点并拼接节点值
XSLT实现同类节点合并并拼接子节点值
需求说明
编写XSLT映射,将XML中同类的productType、orderStatus、orderLineItemStatus节点合并,并将对应子节点(如productTypeValue)的值拼接为逗号分隔的字符串。
输入XML
<Orders> <fromDate>Date</fromDate> <toDate>Date</toDate> <soldTo>String</soldTo> <shipTo>String</shipTo> <endUser>String</endUser> <customerPO>String</customerPO> <orderId>String</orderId> <consigneePO>String</consigneePO> <productType> <productTypeValue>String1</productTypeValue> </productType> <productType> <productTypeValue>String2</productTypeValue> </productType> <orderStatus> <orderStatusValue>String3</orderStatusValue> </orderStatus> <orderStatus> <orderStatusValue>String4</orderStatusValue> </orderStatus> <orderLineItemStatus> <orderLineItemStatusValue>String5</orderLineItemStatusValue> </orderLineItemStatus> <orderLineItemStatus> <orderLineItemStatusValue>String6</orderLineItemStatusValue> </orderLineItemStatus> </Orders>
期望输出XML
<Orders> <fromDate>Date</fromDate> <toDate>Date</toDate> <soldTo>String</soldTo> <shipTo>String</shipTo> <endUser>String</endUser> <customerPO>String</customerPO> <orderId>String</orderId> <consigneePO>String</consigneePO> <productType> <productTypeValue>String1,String2</productTypeValue> </productType> <orderStatus> <orderStatusValue>String3,String4</orderStatusValue> </orderStatus> <orderLineItemStatus> <orderLineItemStatusValue>String5,String6</orderLineItemStatusValue> </orderLineItemStatus> </Orders>
解决方案XSLT代码
<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> <!-- 对Orders下的子节点按节点名分组处理 --> <xsl:template match="Orders"> <xsl:copy> <xsl:for-each-group select="*" group-by="local-name()"> <!-- 处理需要合并的节点类型 --> <xsl:choose> <xsl:when test="local-name() = 'productType' or local-name() = 'orderStatus' or local-name() = 'orderLineItemStatus'"> <!-- 创建合并后的父节点 --> <xsl:element name="{local-name()}"> <!-- 创建对应的子节点,拼接所有分组内的子节点值 --> <xsl:element name="{local-name(*)}"> <xsl:value-of select="current-group()/*" separator=","/> </xsl:element> </xsl:element> </xsl:when> <!-- 其他节点直接复制 --> <xsl:otherwise> <xsl:copy-of select="current-group()"/> </xsl:otherwise> </xsl:choose> </xsl:for-each-group> </xsl:copy> </xsl:template> </xsl:stylesheet>
代码说明
- 身份模板:负责复制XML中大部分不需要修改的节点和属性,保证原有结构不变。
- Orders节点处理模板:
- 使用
<xsl:for-each-group>对Orders的子节点按节点名称分组。 - 针对
productType、orderStatus、orderLineItemStatus这三类节点,创建单个父节点,并通过<xsl:value-of>的separator属性将分组内所有子节点的值拼接为逗号分隔的字符串。 - 其他节点直接复制分组内的内容,保持原有结构。
- 使用
内容的提问来源于stack exchange,提问作者Jagadeesh Kumar
相关产品推荐
相关产品推荐

