如何编写XSLT 1.0模板将多节点指定属性拼接为单个字符串
XSLT 1.0 实现方案
XSLT 1.0 没有内置的序列拼接函数,我们可以通过递归命名模板实现需求,模板接收node参数(传入所有Title节点集合),遍历节点完成属性拼接和逗号分隔:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 递归拼接模板 --> <xsl:template name="concatTitleAttributes"> <!-- 接收节点集合参数 --> <xsl:param name="node" /> <!-- 当前处理的节点位置 --> <xsl:param name="position" select="1" /> <!-- 总节点数量 --> <xsl:param name="totalCount" select="count($node)" /> <!-- 取出当前节点 --> <xsl:variable name="currentNode" select="$node[$position]" /> <!-- 拼接当前节点的属性 --> <xsl:text>Lot </xsl:text> <xsl:value-of select="$currentNode/@lot" /> <xsl:text> </xsl:text> <xsl:value-of select="$currentNode/@plan_type" /> <xsl:text> </xsl:text> <xsl:value-of select="$currentNode/@plan" /> <!-- 不是最后一个节点就加逗号分隔 --> <xsl:if test="$position < $totalCount"> <xsl:text>, </xsl:text> <!-- 递归处理下一个节点 --> <xsl:call-template name="concatTitleAttributes"> <xsl:with-param name="node" select="$node" /> <xsl:with-param name="position" select="$position + 1" /> <xsl:with-param name="totalCount" select="$totalCount" /> </xsl:call-template> </xsl:if> </xsl:template> <!-- 入口模板,匹配根节点 --> <xsl:template match="/RealEstate"> <!-- 调用模板,传入所有Title节点作为参数 --> <xsl:call-template name="concatTitleAttributes"> <xsl:with-param name="node" select="Title" /> </xsl:call-template> </xsl:template> </xsl:stylesheet>
输出结果
对问题提供的示例XML运行上述XSLT,输出结果和需求完全一致:Lot 184 DepositedPlan 1212069, Lot 185 DepositedPlan 1212073, Lot 186 DepositedPlan 1213002
调用说明
如果需要在其他位置调用该模板,只需要将需要处理的同结构节点集合作为node参数传入即可,支持任意数量的节点拼接。
内容的提问来源于stack exchange,提问作者Trent Renshaw
相关产品推荐
相关产品推荐

