如何用XSLT将XML重复属性值合并为单个逗号分隔值
嘿,我来帮你搞定这个问题!你之前的代码是全局抓取了整个文档里所有qa_impacted_fct_areas的值,而我们需要针对每个<contentattributes>节点单独处理它下面的对应属性,还要注意输入里部分name属性带有前后空格的情况(比如" qa_impacted_fct_areas "),得用normalize-space()来统一匹配。
完整XSLT解决方案
假设你使用的是XSLT 2.0或更高版本(支持separator属性),以下代码可以实现你的需求:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"> <!-- 复制根节点 --> <xsl:template match="/root"> <root> <xsl:apply-templates select="contentattributes"/> </root> </xsl:template> <!-- 处理每个contentattributes节点 --> <xsl:template match="contentattributes"> <contentattributes> <!-- 保留其他属性的注释(或根据需求复制实际属性) --> <!--Other Values--> <!-- 合并当前contentattributes下的qa_impacted_fct_areas值 --> <Data ss:Type="String"> <xsl:value-of select="./attribute[normalize-space(@name)='qa_impacted_fct_areas']/@value" separator=", "/> </Data> </contentattributes> </xsl:template> </xsl:stylesheet>
关键细节说明
按节点分组处理:
每个<contentattributes>节点都会被单独处理,只合并当前节点下的qa_impacted_fct_areas属性值,而不是全局所有值。匹配带空格的属性名:
使用normalize-space(@name)='qa_impacted_fct_areas'可以同时匹配name="qa_impacted_fct_areas"和name=" qa_impacted_fct_areas "这类带前后空格的属性,避免遗漏数据。逗号分隔拼接:
通过xsl:value-of的separator=", "属性,直接将多个value值拼接成逗号分隔的字符串,无需额外循环处理。保留其他内容:
如果你需要实际保留原有的其他属性(比如a_archive),可以在<contentattributes>模板里添加如下代码来复制所有非目标属性:<xsl:copy-of select="./attribute[normalize-space(@name)!='qa_impacted_fct_areas']"/>
输出效果
用你提供的输入XML运行上述XSLT,会生成你期望的输出:每个<contentattributes>下对应生成合并后的<Data>节点,值为当前节点下所有qa_impacted_fct_areas属性值的逗号分隔字符串。
内容的提问来源于stack exchange,提问作者Mathi Hari

