XSLT嵌套for-each-group输出兄弟元素唯一组合问题求解
问题原因
你现有代码的问题在于,内层输出cost_center_site值时,用../cost_center_site/ID是提取当前节点父级下所有cost_center_site的ID值,因此会拼接所有站点ID,而非当前循环分组的单个站点值。同时你没有利用current-grouping-key()直接获取当前分组的唯一值,导致重复提取全量字段。
修正后的XSLT代码
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0"> <xsl:output method = "text"/> <xsl:variable name="linefeed" select="'
'"/> <xsl:variable name="delim" select="','"/> <xsl:template match="/*"> <xsl:apply-templates select="Report_Entry" /> </xsl:template> <xsl:template match="Report_Entry"> <xsl:text>cost_center,cost_center_site,gl_company</xsl:text> <xsl:value-of select="$linefeed"/> <xsl:for-each-group select="cost_center" group-by="ID"> <!-- 保存当前成本中心分组ID --> <xsl:variable name="curr_cc" select="current-grouping-key()"/> <xsl:for-each-group select="../cost_center_site" group-by="ID"> <!-- 保存当前站点分组ID --> <xsl:variable name="curr_ccs" select="current-grouping-key()"/> <xsl:for-each-group select="../gl_company" group-by="ID"> <!-- 输出各层当前分组值即可得到唯一笛卡尔积组合 --> <xsl:value-of select="$curr_cc"/> <xsl:value-of select="$delim"/> <xsl:value-of select="$curr_ccs"/> <xsl:value-of select="$delim"/> <xsl:value-of select="current-grouping-key()"/> <xsl:value-of select="$linefeed"/> </xsl:for-each-group> </xsl:for-each-group> </xsl:for-each-group> </xsl:template> </xsl:stylesheet>
补充说明
如果你的输入数据中cost_center、cost_center_site、gl_company的ID本身就没有重复值,也可以直接用嵌套for-each替代for-each-group,去掉group-by属性即可,代码会更简洁。运行上述代码输出结果和你预期完全一致。
内容的提问来源于stack exchange,提问作者user13468980
相关产品推荐
相关产品推荐

