XSLT 1.0实现节点值间添加分隔符的问题求助
问题:XSLT 1.0中为指定节点值添加分隔符
我在XSLT 1.0开发中卡壳了,想请教怎么在指定节点值之间插入分隔符。
源XML
<NtryDtls> <TxDtls> <RmtInf> <Strd> <CdtrRefInf> <Tp> <CdOrPrtry> <Cd>SCOR</Cd> </CdOrPrtry> </Tp> <Ref>VIER000627054</Ref> </CdtrRefInf> </Strd> </RmtInf> </TxDtls> </NtryDtls>
当前使用的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:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:for-each select="NtryDtls/TxDtls/RmtInf"> <xsl:for-each select="*"> <xsl:for-each select="node() | @*"> <xsl:value-of select="."/> <xsl:if test="not(position()=last()) ">,</xsl:if> </xsl:for-each> </xsl:for-each> </xsl:for-each> </xsl:template> </xsl:stylesheet>
当前输出结果
,SCORVIER000627054,
期望输出结果
SCOR, VIER000627054
解决方案
原代码的问题在于遍历了所有节点(包括元素节点本身,这类节点的文本内容为空,导致出现多余逗号),且没有精准定位到需要提取值的Cd和Ref节点。可以直接定位到目标节点,再处理分隔符:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <!-- 精准定位到需要取值的Cd和Ref节点 --> <xsl:for-each select="NtryDtls/TxDtls/RmtInf/Strd/CdtrRefInf//*[self::Cd or self::Ref]"> <xsl:value-of select="."/> <!-- 非最后一个节点时添加分隔符 ", " --> <xsl:if test="position() != last()">, </xsl:if> </xsl:for-each> </xsl:template> </xsl:stylesheet>
说明
- 将输出方法改为
text,避免生成XML结构,直接输出文本内容 - 通过
//*[self::Cd or self::Ref]精准筛选出需要提取值的节点 - 遍历这些节点时,仅在非最后一个节点后添加
,分隔符,避免首尾出现多余符号
运行上述代码后,即可得到期望的输出结果。
内容的提问来源于stack exchange,提问作者smokey
相关产品推荐
相关产品推荐

