Flatten xml hierarchy using XSLT

saravana perumal Raj

I would like to convert a nested xml to flatten xml using XSLT.

Incoming xml Structure would be similar but the node names would change for the incoming xmls, so would like to handle in dynamically

Sample input

<?xml version="1.0" encoding="UTF-8"?>
<queryResponse>
  <Account>
    <Id>0010</Id>
    <Name>AA</Name>
    <RecordTypeId>0122/RecordTypeId>
    <RecordType>
      <Id>012</Id>
      <DeveloperName>Legal_Associate</DeveloperName>
    </RecordType>
  </Account>
  <Account>
    <Id>0011</Id>
    <Name>BB</Name>
    <RecordTypeId>0123</RecordTypeId>
    <RecordType>
      <Id>013</Id>
      <DeveloperName>Legal_Associate</DeveloperName>
    </RecordType>
  </Account>
 </queryResponse>

Expected Output

<?xml version="1.0" encoding="UTF-8"?>
<queryResponse>
  <Account>
    <Id>0010</Id>
    <Name>AA</Name>
    <RecordTypeId>0122</RecordTypeId>
    <RecordType.Id>012</RecordType.Id>
  <RecordType.DeveloperName>Legal_Associate</RecordType.DeveloperName>
  </Account>
  <Account>
    <Id>0011</Id>
    <Name>BB</Name>
    <RecordTypeId>0123<RecordTypeId>
    <RecordType.Id>013</RecordType.Id>    <RecordType.DeveloperName>Legal_Associate</RecordType.DeveloperName>
    </Account>
    </queryResponse>

Amrendra Kumar

While posting the question you should post the tried code as well hense we can tell you the updation.

Here is the code which you can achive your answer:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    exclude-result-prefixes="xs" version="2.0">

    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="RecordType">
        <xsl:for-each select="*">
            <xsl:element name="{concat(name(..),'.',name())}">
                <xsl:apply-templates select="node()"/>
            </xsl:element>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related