XSLT 2.0分组转换:如何为每个LogistiekeDeelEenheid匹配正确数值
嘿,我完全懂你的困扰——你已经成功给每个<LogistiekeDeelEenheid>完成分组,但<DeeleenheidAantal>现在会把所有数值(10、20、35)一股脑显示出来,而不是每个DeelEenheid对应自己的专属数值对吧?这问题本质是没建立起<LogistiekeDeelEenheid>和对应<ProductCrossReference>下数值的精准关联,之前的代码大概率是全局选取了所有<Value>节点,才导致数值串在一起。
我给你一个XSLT里最常用的解决方案,用key功能实现一对一匹配:
1. 核心思路拆解
我们需要先给原XML里的<ProductCrossReference>节点建立一个“索引映射”,把每个<LogistiekeDeelEenheid>的值和它对应的<Value AttributeID="att_AantalInCombiProduct">数值绑定,这样处理每个DeelEenheid时,就能直接定位到对应的数值。
2. 具体实现步骤
假设你的原XML结构大概是这样(如果实际结构有差异,只需要调整关联字段即可):
<Root> <CombiProduct> <LogistiekeDeelEenheid>000094</LogistiekeDeelEenheid> </CombiProduct> <CombiProduct> <LogistiekeDeelEenheid>000072</LogistiekeDeelEenheid> </CombiProduct> <CombiProduct> <LogistiekeDeelEenheid>000032</LogistiekeDeelEenheid> </CombiProduct> <ProductCrossReference> <AssociatedID>000094</AssociatedID> <!-- 这个ID和LogistiekeDeelEenheid的值一一对应 --> <Value AttributeID="att_AantalInCombiProduct">10</Value> </ProductCrossReference> <ProductCrossReference> <AssociatedID>000072</AssociatedID> <Value AttributeID="att_AantalInCombiProduct">20</Value> </ProductCrossReference> <ProductCrossReference> <AssociatedID>000032</AssociatedID> <Value AttributeID="att_AantalInCombiProduct">35</Value> </ProductCrossReference> </Root>
第一步:定义关联键
在XSLT的<xsl:stylesheet>内部顶部,添加一个key来建立映射关系:
<xsl:key name="aantalMapping" match="ProductCrossReference" use="AssociatedID"/> <!-- 这里填和LogistiekeDeelEenheid对应的关联字段 -->
第二步:处理每个DeelEenheid时匹配数值
在处理<LogistiekeDeelEenheid>的模板里,用刚才定义的key精准提取对应数值:
<xsl:template match="LogistiekeDeelEenheid"> <Deeleenheid> <LogistiekeDeelEenheid><xsl:value-of select="."/></LogistiekeDeelEenheid> <DeeleenheidAantal> <!-- 用当前DeelEenheid的值作为键,找到对应的ProductCrossReference,再取出目标Value --> <xsl:value-of select="key('aantalMapping', .)/Value[@AttributeID='att_AantalInCombiProduct']"/> </DeeleenheidAantal> </Deeleenheid> </xsl:template>
3. 为什么这个方法有效?
之前你的代码可能用了类似//Value[@AttributeID='att_AantalInCombiProduct']的全局选择,会把所有符合条件的<Value>值都拼接输出。而用key相当于给每个DeelEenheid值开了一个“专属通道”,只会取出和它匹配的那一个数值。
如果你的原XML中,<LogistiekeDeelEenheid>和<ProductCrossReference>的关联字段不是AssociatedID,只需要把key里的use属性改成对应的字段(比如产品编码、ID标识等)就行,核心逻辑不变。
内容的提问来源于stack exchange,提问作者Africa

