我试图获得使用xslt的分组优化。优化应该将具有相同名称的项目收集到单个项目元素中。当它们都处于同一级别时,我有它的工作,但有些输入将它们嵌套在任意级别,我无法弄清楚如何让这些分组在这些情况下工作。xslt按照名称在多个嵌套层次上分组项目
这里有一个工作示例:
<process>
<op>
<group>
<op>
<item>
<name>a</name>
<detail><value>1</value></detail>
</item>
</op>
<op>
<item>
<name>a</name>
<detail><value>2</value></detail>
</item>
</op>
<op>
<item>
<name>c</name>
<name>x1</name>
<detail><value>3</value></detail>
</item>
</op>
</group>
</op>
,这里是我的榜样变换定义:
<xs:template match="group[op[item[detail]]]">
<xs:copy>
<xs:for-each-group select="op" group-by="item/name">
<op><item>
<xs:copy-of select="item/name"/>
<xs:choose>
<xs:when test="count(current-group()) > 1">
<details>
<xs:for-each select="current-group()">
<detail><value>
<xs:value-of select="item/detail/value"/>
</value></detail>
</xs:for-each>
</details>
</xs:when>
<xs:otherwise>
<detail><value>
<xs:value-of select="item/detail/value"/>
</value></detail>
</xs:otherwise>
</xs:choose>
</item></op>
</xs:for-each-group>
</xs:copy>
</xs:template>
<xs:template match="@*|node()">
<xs:copy>
<xs:apply-templates select="@*|node()"/>
</xs:copy>
</xs:template>
哪个正确组 “一” 项目一起,留下“c”项目分开。 然而,如果 “A” 的数据项都进一步嵌套的,它们getted跌出结果:
<process>
<op>
<group>
<op>
<group>
<op>
<item>
<name>a</name>
<detail><value>1</value></detail>
</item>
</op>
<op>
<item>
<name>a</name>
<detail><value>2</value></detail>
</item>
</op>
</group>
</op>
<op>
<item>
<name>c</name>
<name>x1</name>
<detail><value>3</value></detail>
</item>
</op>
</group>
</op>
期望得到的XML将是:
<process>
<op>
<group>
<op>
<group>
<op>
<item>
<name>a</name>
<details>
<detail><value>1</value></detail>
<detail><value>2</value></detail>
</details>
</item>
</op>
</group>
</op>
<op>
<item>
<name>c</name>
<name>x1</name>
<detail><value>3</value></detail>
</item>
</op>
</group>
</op></process>
(如果多个条目'c'和'x1'都存在,它们也可以分组,但这不是必需的)
需要说明和解释而导致你想为你的最后一个输入样本,这是我不清楚。 –
添加了所需的结果xml – mjoen
所以,你想保留层次结构,并基本上在每个“组”中包含“op”元素。如果有'op'元素带有'item''c,然后是嵌套组,然后一些'op'元素带有'item''c',会发生什么?你想把所有'c'项目组合在一起,基本上拉起后面的元素吗?或者,如果在原始XML中相邻,那么你是否只想将'op'元素与相同的'item'分组? –