User2300
User2300

Reputation: 35

Removing Child nodes in XML and copying their data to parent node using XSLT

I am trying to eliminate all the child nodes and copy all the data to the parent node but the output remains the same as the input.

Input XML -

<?xml version="1.0" encoding="ISO-8859-1"?>
<PersonData>    
    <Header>
    </Header>
    <Person>
      <Personal>
         <FirstName>abc</FirstName>
         <LastName>cde</LastName>
         <ID>12345</ID>
      </Personal>
      <AddressData>
         <Address1>abc123</Address1>
         <Address2>def345</Address2>
      </AddressData>
      <PhoneData>
         <Phone1>111111111</Phone1>
      </PhoneData>
    </Person>
 </PersonData>

I have already tried the below code but the output remains the same as input thus not removing child nodes and the data as well remaining within them not moving to parent node i.e. Person.

   <?xml version='1.0'?>
   <xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="xml" indent="yes"/>
   <xsl:strip-space elements="*" />

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

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

   </xsl:stylesheet>    

Desired Output -

   <?xml version="1.0" encoding="ISO-8859-1"?>
   <PersonData>    
   <Person>
     <FirstName>abc</FirstName>
     <LastName>cde</LastName>
     <ID>12345</ID>
     <Address1>abc123</Address1>
     <Address2>def345</Address2>
     <Phone1>111111111</Phone1>
    </Person>
    </PersonData>

I get the same output as input XML and not the above expected output without child nodes

Upvotes: 1

Views: 234

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

How about:

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:strip-space elements="*"/>

<xsl:template match="/PersonData">
    <xsl:copy>
        <xsl:apply-templates select="Person"/>
     </xsl:copy>
</xsl:template>

<xsl:template match="Person">
    <xsl:copy>
        <xsl:copy-of select="*/*"/>
     </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions