Search code examples
xsltxslt-2.0

Concatenating repeated XML element result in single row XSLT


I am trying to concatenate the repeating OrderID into single row output with delimiter comma(,). buy my xslt is not giving expected output. Any light thrown on this would be appreciated.

My XML Input

<?xml version="1.0" encoding="UTF-8" ?>
 <EventsRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Event>
   <Item>
     <ID>ID1</ID>
     <TABLE_NAME>TABLE_NAME</TABLE_NAME>        
     <ORDERID>111,US</ORDERID>
     <STATUS>INPROGRESS</STATUS>
     <ACTION>ADD</ACTION>
     <SUBSCRIBED_BY>AAA</SUBSCRIBED_BY>        
   </Item>
   <Item>
     <ID>ID12</ID>
     <TABLE_NAME>TABLE_NAME</TABLE_NAME>        
     <ORDERID>222,US</ORDERID>
     <STATUS>INPROGRESS</STATUS>
     <ACTION>ADD</ACTION>
     <SUBSCRIBED_BY>BBB</SUBSCRIBED_BY>      
   </Item>
  </Event>  
 </EventsRequest>

My XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/">
  <xsl:for-each select="EventsRequest/Event/Item">
     <xsl:for-each select="tokenize(ORDERID, ',')">
        <DAILIYORDERS>
           <OrderIds>
              <xsl:value-of select="concat(.,',')"/>
           </OrderIds>
        </DAILIYORDERS>
     </xsl:for-each>
    </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

Current Output

<?xml version="1.0" encoding="UTF-8"?>  
<DAILIYORDERS>
<OrderIds>111</OrderIds>  
</DAILIYORDERS>
<DAILIYORDERS>  
<OrderIds>222</OrderIds>
</DAILIYORDERS>

Expected Output

  <?xml version="1.0" encoding="UTF-8"?>
<DAILIYORDERS>
  <OrderIds>111,222</OrderIds>
</DAILIYORDERS>

Solution

  • The result you expect can be obtained simply by:

    XSLT 2.0

    <xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:template match="/EventsRequest">
        <DAILIYORDERS>
            <OrderIds>
                <xsl:value-of select="Event/Item/substring-before(ORDERID, ',')" separator=","/>
            </OrderIds>
        </DAILIYORDERS>
    </xsl:template>
    
    </xsl:stylesheet>