0

I am trying to create an XSLT to transform my XML into a specific format that then gets transformed into JSON.

My sample file looks like this:

<?xml version='1.0' encoding='UTF-8'?>
<RegResults>
    <RegInfo>
        <tradingPartnerId>12345</tradingPartnerId>
        <ediTransactionCode>204</ediTransactionCode>
    </RegInfo>
    <RegInfo>
        <tradingPartnerId>12345</tradingPartnerId>
        <ediTransactionCode>214</ediTransactionCode>
    </RegInfo>
    <RegInfo>
        <tradingPartnerId>23456</tradingPartnerId>
        <ediTransactionCode>204</ediTransactionCode>
    </RegInfo>
    <RegInfo>
        <tradingPartnerId>23456</tradingPartnerId>
        <ediTransactionCode>214</ediTransactionCode>
    </RegInfo>
</RegResults>

After the XSLT transformation, my output XML should look like this:

<tradingPartnerId>12345</tradingPartnerId>
    <ediTransactionCode>204</ediTransactionCode>
    <ediTransactionCode>214</ediTransactionCode>
<tradingPartnerId>23456</tradingPartnerId>
    <ediTransactionCode>204</ediTransactionCode>
    <ediTransactionCode>214</ediTransactionCode>

The goal is to ultimately transform the XML in the previous transformation into the following JSON (which is done by a service in my application):

{
  "tradingPartnerId": "12345",
  "ediTransactionCodes": [
    "204",
    "214"
  ]
"tradingPartnerId": "23456",
  "ediTransactionCodes": [
    "204",
    "214"
  ]
}

I have to use XSLT 1.0. I tried using 'distinct-values' in an online formatter, which I believe is an XSLT 2.0 function, nevertheless, I am not receiving the XML output I need. Here is the XSLT I tried, but clearly it is wrong:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <xsl:for-each select="distinct-values(//*[local-name()='tradingPartnerId'])">
            <tradingPartnerId>
                <xsl:value-of select="."/>
                <xsl:for-each select="distinct-values(//*[local-name()='ediTransactionCode'])">
                    <ediTransactionCode>
                        <xsl:value-of select="."/>
                    </ediTransactionCode>
                </xsl:for-each>
            </tradingPartnerId>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Any assistance is appreciated.

  • 1
    This is a [grouping](https://stackoverflow.com/tags/xslt-grouping/info) problem - and grouping in XSLT 1.0 is best done using the Muenchian method: http://www.jenitennison.com/xslt/grouping/muenchian.html. -- Note that the output you show is an XML fragment, not a well-formed XML document (no single root element). – michael.hor257k Nov 23 '21 at 00:59
  • P.S. There is never a need to use a hack like `*[local-name()='xyz]`. If your input has namespaces, deal with them: https://stackoverflow.com/a/34762628/3016153 – michael.hor257k Nov 23 '21 at 01:02

0 Answers0