xmlcsvxsltxpath

XSLT Iterate convert to CSV


Can someone help me in transforming below xml to csv(in below format).

XML:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header>
      <Shop>Walmart</Shop>
  </soapenv:Header>
  <soapenv:Body>
    <ResponseEnvelope>
      <Response>
        <Part_electronics>
          <type>electronics</type>
          <item>Freeze</item>
        </Part_electronics>
        <Part_utility>
          <type>utility</type>
          <item>Parker</item>
        </Part_utility>
        <Part_grocery>
          <type>grocery</type>
          <item>sugar</item>
        </Part_grocery>
      </Response>
    </ResponseEnvelope>
  </soapenv:Body>
</soapenv:Envelope>

CSV putput:

Walmart,electronics,Freeze
Walmart,utility,pen
Walmart,grocery,sugar

Solution

  • It looks like you want row for every "part_" element. In this case, you should start off by selecting those elements

    <xsl:for-each select="//Response/*[starts-with(local-name(), 'Part_')]">
    

    Then you can get the fields, by selecting all the children

         <xsl:for-each select="*">
             <xsl:text>,</xsl:text>
             <xsl:value-of select="text()" />
         </xsl:for-each>
    

    This assumes all the "Part_" elements have the same number of elements in the same order.

    Try this XSLT

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
       <xsl:output method="text" indent="yes"/> 
       <xsl:template match="/">
          <xsl:variable name="Shop" select="//Shop" />
          <xsl:for-each select="//Response/*[starts-with(local-name(), 'Part_')]"> 
             <xsl:value-of select="$Shop"/> 
             <xsl:for-each select="*">
                 <xsl:text>,</xsl:text>
                 <xsl:value-of select="text()" />
             </xsl:for-each>
             <xsl:text>&#xA;</xsl:text>
          </xsl:for-each> 
       </xsl:template> 
    </xsl:stylesheet>
    

    This outputs the following:

    Walmart,electronics,Freeze
    Walmart,utility,Parker
    Walmart,grocery,sugar