我的输入 xml 如下所示:
<items>
<item>
<geoDetails>
<street>xxx</street>
<city>yyy</city>
<state>zzz</state>
</geoDetails>
<otherDetails>
<desc>abcd111</desc>
<comments>good item</comments>
</otherDetails>
<key>
<name>item1</name>
<id>123</id>
<color>red</color>
</key>
<misc>
<available>false</available>
<details>geo</details>
</misc>
</item>
<item>
<otherDetails>
<desc>efgh222</desc>
<comments>good item</comments>
</otherDetails>
<key>
<name>item2</name>
<id>123</id>
<color>red</color>
</key>
<misc>
<available>false</available>
<details>other</details>
</misc>
</item>
<item>
<geoDetails>
<street>ppp</street>
<city>qqq</city>
<state>rrr</state>
</geoDetails>
<otherDetails>
<desc>ijkl333</desc>
<comments>best item</comments>
</otherDetails>
<key>
<name>item3</name>
<id>456</id>
<color>blue</color>
</key>
<misc>
<available>false</available>
<details>other</details>
</misc>
</item>
</items>
对“item”节点进行分组的关键是 concat(/items/item/key/id,/items/item/key/color) 对于每个标识的组,合并应该按照以下给出的逻辑进行:
一种。从 misc/details 为“geo”的“item”中提取“geoDetails”。
湾。从 misc/details 为“other”的“item”中提取“otherDetails”。每个“项目”中只有一个杂项/详细信息,其值为“地理”或“其他”。
C。从给定组中的第一个“项目”中提取“关键”元素。
d。'misc' 元素应该包含'available' 元素(这总是'false',因此填充一次就足够了)并且'details' 元素应该具有基于元素'geoDetails' 或'otherDetails' 填充的值通过上述步骤 a 和 b 中给出的逻辑。如果同时填充了“geoDetails”和“otherDetails”,则应该有 2 个“详细信息”元素。
e. 任何其他不属于组的单个“项目”元素都应该按原样推送到输出。
基于上述逻辑的预期输出如下图所示:
<items>
<item>
<geoDetails>
<street>xxx</street>
<city>yyy</city>
<state>zzz</state>
</geoDetails>
<otherDetails>
<desc>efgh222</desc>
<comments>good item</comments>
</otherDetails>
<key>
<name>item1</name>
<id>123</id>
<color>red</color>
</key>
<misc>
<available>false</available>
<details>geo</details>
<details>other</details>
</misc>
</item>
<item>
<geoDetails>
<street>ppp</street>
<city>qqq</city>
<state>rrr</state>
</geoDetails>
<otherDetails>
<desc>ijkl333</desc>
<comments>best item</comments>
</otherDetails>
<key>
<name>item3</name>
<id>456</id>
<color>blue</color>
</key>
<misc>
<available>false</available>
<details>other</details>
</misc>
</item>
我使用 xsl:key 和 apply-templates 尝试了基于 Muenchian 分组的转换。我能够对“项目”元素进行分组,但无法根据上述条件进一步合并这些分组元素。
XSLT 转换:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" version="1.0" exclude-result-prefixes="exsl">
<xsl:key match="item" name="itemKey" use="concat(key/id,key/color)" />
<xsl:template match="/">
<xsl:variable name="output">
<xsl:apply-templates />
</xsl:variable>
<xsl:copy-of select="exsl:node-set($output)/*" />
</xsl:template>
<!-- default template -->
<xsl:template match="node( ) | @*">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match="item[generate-id(.)=generate-id(key('itemKey',concat(key/id,key/color))[1])]">
<xsl:copy>
<xsl:apply-templates select="@* | key('itemKey',concat(key/id,key/color))/node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="item" />
我已经解决了 Stackoverflow 上的几个相关问题,但无法使合并过程适应我当前的情况。任何帮助是极大的赞赏。