Frage

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.

War es hilfreich?

Lösung

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)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top