I am trying to eliminate child nodes and copy their data to parent node. For Example,
<?xml version="1.0" encoding="utf-8"?>
<root>
<data>
<School>
<Name>
<Data>
<FirstName>DonaldDuck</FirstName>
</Data>
</Name>
</School>
</data>
</root>
Desired output is
<?xml version="1.0" encoding="utf-8"?>
<root>
<data>
<School>
<Name>DonaldDuck</Name>
</School>
</data>
</root>
I have tried using below code but it did not work as expected
<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="root/data">
<xsl:copy>
<xsl:apply-templates select="school"/>
</xsl:copy>
</xsl:template>
<xsl:template match="school">
<xsl:copy>
<xsl:copy-of select="*/*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Any help would be highly appreciated.
You can achieve your goal by combining the Identity template with a simple replacement template:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<!-- identity template -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="Name">
<xsl:copy>
<xsl:value-of select="Data/FirstName" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
This replaces the value of all Name
elements with the value of its Data/FirstName
child. If you wanted to replace any child of a child, you should use the */*
axis instead - as you did in the example.
In both cases, its output is:
<?xml version="1.0"?>
<root>
<data>
<School>
<Name>DonaldDuck</Name>
</School>
</data>
</root>
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.