xml - XSLT: Group different element types -
my source xml looks follows:
<a> <item> <x>10</x> <y>20</y> <data1>foo</data1> </item> </a> <b> <item> <x>10</x> <y>20</y> <data2>bar</data2> </item> </b> <a> <item> <x>11</x> <y>20</y> <data1>foo2</data1> </item> </a> <b> <item> <x>11</x> <y>20</y> <data2>bar2</data2> </item> </b>
note a
s , b
s occur pairwise respect values of x
, y
. note there other elements containing nested item
element should ignored. now, goal group elements having same values x
, y
new elements looking this:
<newelement> <x>10</x> <y>20</y> <data1>foo</data1> <data2>bar</data2> </newelement> <newelement> <x>11</x> <y>20</y> <data1>foo2</data1> <data2>bar2</data2> </newelement>
i have read muenchian grouping, seems works same elements (e.g., in example group a
s having same values x
and y
). how can group different elements?
the following stylesheet:
xslt 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/> <xsl:key name="b" match="b/item" use="concat(x, '|', y)" /> <xsl:template match="/root"> <root> <xsl:for-each select="a/item"> <newelement> <xsl:copy-of select="*"/> <xsl:copy-of select="key('b', concat(x, '|', y))/data2"/> </newelement> </xsl:for-each> </root> </xsl:template> </xsl:stylesheet>
applied input example (after adding root
element make well-formed!), produces:
<?xml version="1.0" encoding="utf-8"?> <root> <newelement> <x>10</x> <y>20</y> <data1>foo</data1> <data2>bar</data2> </newelement> <newelement> <x>11</x> <y>20</y> <data1>foo2</data1> <data2>bar2</data2> </newelement> </root>
Comments
Post a Comment