用xslt和子节点分组 [英] Grouping with xslt and child nodes
问题描述
我在这里尝试了一些示例,但是仍然无法获得正确的输出.之前,我对XSLT的工作并不多.我想对详细信息"元素进行分组,并将与该组匹配的所有数据"元素作为子元素添加到详细信息"元素.
I have tried some of the examples here, but I still can't get the correct output. I haven't worked much with XSLT before. I want to group on the "Detail" element and get all the "Data" elements matching that group as children to the "Detail" element.
示例:
输入
<?xml version="1.0" encoding="utf-8"?>
<File>
<Detail type="A" group="1" >
<Data>
<Nr>1</Nr>
</Data>
<Data>
<Nr>2</Nr>
</Data>
</Detail>
<Detail type="B" group="1">
<Data>
<Nr>3</Nr>
</Data>
<Data>
<Nr>4</Nr>
</Data>
</Detail>
<Detail type="B" group="2">
<Data>
<Nr>5</Nr>
</Data>
</Detail>
<Detail type="A" group="1">
<Data>
<Nr>6</Nr>
</Data>
</Detail>
</File>
想要的输出("Detail type =" A"group =" 1>元素组合在一起,并且所有与该组匹配的元素都作为子元素
Wanted output ("Detail type="A" group="1"> elements grouped together and all the elements matching that group as children)
<?xml version="1.0" encoding="utf-8"?>
<File>
<Detail type="A" group="1" >
<Data>
<Nr>1</Nr>
</Data>
<Data>
<Nr>2</Nr>
</Data>
<Data>
<Nr>6</Nr>
</Data>
</Detail>
<Detail type="B" group="1">
<Data>
<Nr>3</Nr>
</Data>
<Data>
<Nr>4</Nr>
</Data>
</Detail>
<Detail type="B" group="2">
<Data>
<Nr>5</Nr>
</Data>
</Detail>
</File>
感谢您的帮助:)
推荐答案
注意:在我拿起书包之前,这个问题在垃圾箱中搁置了6个小时.我的答案在垃圾箱中停滞了两个小时,然后其他人掩盖了一些不必要的评论作为答案.
NOTE: This question languished in the bin for 6 hours before I took it up. My answer languished in the bin for two hours before someone else disguised some non-essential comments as an answer.
研究Muenchian分组.对于这些分组问题很方便.
Study up on Muenchian grouping. It's handy for these grouping problems.
重型起重器是< xsl:key>
,它基于@type和@group的连接创建密钥,此处的行是< xsl:for-每个select ="File/Detail [count(.| key('details',concat(@type,'_',@ group))[1])= 1]">
,将第一个隔离细节节点出现时具有特定的键,并通过扩展将@group和@type进行特定的配对.
The heavy lifters are <xsl:key>
, which creates a key based on a concat of @type and @group, and this line here, <xsl:for-each select="File/Detail[count(. | key('details', concat(@type,'_',@group))[1]) = 1]">
, which isolates the first occurrence of the Detail node having a particular key and by extension a particular pairing of @group and @type.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:key name="details" match="Detail"
use="concat(@type,'_',@group)"/>
<xsl:template match='/'>
<File>
<xsl:for-each select="File/Detail[count(. | key('details', concat(@type,'_',@group))[1]) = 1]">
<xsl:sort select="concat(@type,'_',@group)" />
<Detail type="{@type}" group="{@group}">
<xsl:for-each select="key('details', concat(@type,'_',@group))">
<xsl:copy-of select="Data"/>
</xsl:for-each>
</Detail>
</xsl:for-each>
</File>
</xsl:template>
</xsl:stylesheet>
这篇关于用xslt和子节点分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!