XSLT需求:合并重复LineTransaction字段生成合规JSON
解决Workday XML转JSON时LineTransaction键重复的问题
问题背景
现有Workday格式的XML数据中,wd:InvoiceLine节点下包含多个wd:LineTransaction子节点。用原有XSLT转换后生成的JSON会出现重复的LineTransaction键,不符合预期。需要修改XSLT,把多个LineTransaction节点的@wd:Descriptor属性值用分号拼接,合并为单个LineTransaction键对应的取值,生成符合要求的JSON输出。
原XML示例
<wd:Invoice> <wd:InvoiceLine> <wd:LineTransaction wd:Descriptor="Transaction A"/> <wd:LineTransaction wd:Descriptor="Transaction B"/> <wd:LineTransaction wd:Descriptor="Transaction C"/> </wd:InvoiceLine> </wd:Invoice>
原XSLT代码
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wd="urn:com.workday/bsvc"> <xsl:output method="json" indent="yes"/> <xsl:template match="/"> <xsl:text>{</xsl:text> <xsl:apply-templates select="wd:Invoice/wd:InvoiceLine"/> <xsl:text>}</xsl:text> </xsl:template> <xsl:template match="wd:InvoiceLine"> <xsl:for-each select="wd:LineTransaction"> <xsl:text>"LineTransaction": "</xsl:text> <xsl:value-of select="@wd:Descriptor"/> <xsl:text>",</xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet>
当前错误输出
{ "LineTransaction": "Transaction A", "LineTransaction": "Transaction B", "LineTransaction": "Transaction C" }
预期输出
{ "LineTransaction": "Transaction A;Transaction B;Transaction C" }
修改后的XSLT代码
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wd="urn:com.workday/bsvc"> <xsl:output method="json" indent="yes"/> <xsl:template match="/"> <xsl:text>{</xsl:text> <xsl:apply-templates select="wd:Invoice/wd:InvoiceLine"/> <xsl:text>}</xsl:text> </xsl:template> <xsl:template match="wd:InvoiceLine"> <xsl:text>"LineTransaction": "</xsl:text> <!-- 用string-join拼接所有LineTransaction的Descriptor属性,分号分隔 --> <xsl:value-of select="string-join(wd:LineTransaction/@wd:Descriptor, ';')"/> <xsl:text>"</xsl:text> </xsl:template> </xsl:stylesheet>
修改说明
把原XSLT里循环输出每个LineTransaction键值对的逻辑,换成用string-join()函数一次性拼接所有wd:LineTransaction节点的@wd:Descriptor属性值,用分号做分隔符,这样就能生成单个LineTransaction键对应拼接后的值,彻底解决JSON键重复的问题。
内容的提问来源于stack exchange,提问作者Mahari
相关产品推荐
相关产品推荐

