循环拼接XML元素并添加分隔符的XSLT实现问题求助
问题描述
需要遍历XML中的DocumentPayable节点,将每个节点下的ReferenceNumber值拼接成以/分隔的字符串,预期输出为TEST_003/TEST_004/TEST_005,且最终字符串长度不超过140字符。
输入XML数据
<OutboundPaymentInstruction> <DocumentPayable> <DocumentNumber> <ApplicationInternalID>200</ApplicationInternalID> <ReferenceNumber>TEST_003</ReferenceNumber> <DocCategory>STD INV</DocCategory> <SequenceName>SEQ1</SequenceName> <SequenceValue>520822000792</SequenceValue> </DocumentNumber> </DocumentPayable> <DocumentPayable> <DocumentNumber> <ApplicationInternalID>200</ApplicationInternalID> <ReferenceNumber>TEST_004</ReferenceNumber> <DocCategory>STD INV</DocCategory> <SequenceName>SEQ1</SequenceName> <SequenceValue>520822000792</SequenceValue> </DocumentNumber> </DocumentPayable> <DocumentPayable> <DocumentNumber> <ApplicationInternalID>200</ApplicationInternalID> <ReferenceNumber>TEST_005</ReferenceNumber> <DocCategory>STD INV</DocCategory> <SequenceName>SEQ1</SequenceName> <SequenceValue>520822000792</SequenceValue> </DocumentNumber> </DocumentPayable> </OutboundPaymentInstruction>
尝试的XSLT代码(输出不符合预期)
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="OutboundPaymentInstruction"> <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <xsl:variable name="Invoices" select="DocumentNumber/ReferenceNumber"/> <Ustrd> <xsl:for-each select="DocumentPayable/DocumentNumber"> <xsl:choose> <xsl:when test="position() = 1"> <xsl:value-of select="ReferenceNumber"/> </xsl:when> <xsl:otherwise> /<xsl:value-of select="ReferenceNumber"/> </xsl:otherwise> </xsl:choose> </xsl:for-each> </Ustrd> </Document> </xsl:template> </xsl:stylesheet>
解决方案
你的XSLT代码问题出在输出的文本包含多余的空白字符——<otherwise>块里的/前面有大量缩进空格,导致最终拼接的字符串夹杂这些空格。另外,还需要添加长度限制逻辑确保最终字符串不超过140字符。
修改后的XSLT代码如下:
<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="OutboundPaymentInstruction"> <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Ustrd> <!-- 先拼接所有ReferenceNumber为/分隔的字符串 --> <xsl:variable name="fullString"> <xsl:for-each select="DocumentPayable/DocumentNumber"> <xsl:if test="position() > 1">/</xsl:if> <xsl:value-of select="ReferenceNumber"/> </xsl:for-each> </xsl:variable> <!-- 截取前140字符,确保长度符合要求 --> <xsl:value-of select="substring($fullString, 1, 140)"/> </Ustrd> </Document> </xsl:template> </xsl:stylesheet>
修改说明
- 移除多余空白:把
<otherwise>的逻辑换成<xsl:if test="position() > 1">/</xsl:if>,避免缩进空格混入输出字符串。 - 添加长度限制:先用变量存储完整的拼接字符串,再通过
substring($fullString, 1, 140)截取前140个字符,满足长度要求。 - 简化逻辑:去掉了无用的
Invoices变量,代码更简洁高效。
内容的提问来源于stack exchange,提问作者Arun M
相关产品推荐
相关产品推荐

