Reputation: 1648
I have an XML file like the below where I may have multiple records with a common child element like so:
<person>
<name>Alice</name>
<account>001</account>
</person>
<person>
<name>Alice</name>
<account>002</account>
</person>
How would I transform this to the below using XSLT 2.0?
<person>
<name>Alice</name>
<account>001,002</account>
</person>
I'm fairly new to XSLT so please excuse the potentially novice question. Any guidance would be appreciated here. Thanks in advance.
Upvotes: 1
Views: 669
Reputation: 122364
You can use for-each-group
to group the person
elements, and the separator
attribute on value-of
to build the comma-separated value:
<xsl:for-each-group select="person" group-by="name">
<person>
<xsl:sequence select="name" /><!-- copy the name element -->
<account>
<xsl:value-of select="current-group()/account" separator="," />
</account>
</person>
</xsl:for-each-group>
(assuming your current context node is the parent of the person
elements - if it is not then you'll have to adjust the for-each-group
select
expression appropriately)
Upvotes: 2