简体   繁体   中英

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 ie 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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM