1
votes

I am having a really hard time trying to group different elements by a common value using XSLT 1.0.

Using the following XML:

<root>
    <segment>
        <id>ABCD123</id>
    </segment>
    <segment>
        <contact>
            <field1>ABCD123</field1>
            <field2>(111)345-7890</field2>
        </contact>
    </segment>
    <segment>
        <details>
            <field1>ABCD123</field1>
            <field5>More Details for ABCD123</field5>
        </details>
    </segment>
    <segment>
        <id>XZX098</id>
    </segment>
    <segment>
        <contact>
            <field1>XZX098</field1>
            <field2>(111)443-9999</field2>
        </contact>
    </segment>
    <segment>
        <details>
            <field1>XZX098</field1>
            <field5>More Details for XZX098</field5>
        </details>
    </segment>
</root>

Transform into this:

<File>
    <Record>
        <id>ABCD123</id>
        <phone>(111)345-7890</phone>
        <details>More Details for ABCD123</details>
    </Record>
    <Record>
        <id>XZX098</id>
        <phone>(111)443-9999</phone>
        <details>More Details for XZX098</details>
    </Record>
</File>

I'm trying to group records by the 'id', and then get the contact, and details information that matches that 'id'.

Any help is greatly appreciated.

1
Your XML sample is too small to deduct a system from it. Please extend you XML files and also add an attempt to solve it.zx485

1 Answers

0
votes

I don't see any grouping per se required here - just a simple lookup of cross-referenced data:

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="contact-details" match="contact|details" use="field1" />

<xsl:template match="root">
    <File>
        <xsl:for-each select="segment/id">
            <Record>
                <xsl:copy-of select="."/>
                <phone>
                    <xsl:value-of select="key('contact-details', .)/field2"/>
                </phone>
                <details>
                    <xsl:value-of select="key('contact-details', .)/field5"/>
                </details>
            </Record>
        </xsl:for-each>
    </File>
</xsl:template>

</xsl:stylesheet>