What is the xslt select statement to transofrm xml from
<A> <B id="x"> <C> <D> <D> <D> <D> </C> </B> </A> to
<C name = "x"> <D> <D> <D> <D> </C> Here is a short and simple, complete solution:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="B[@id]/C"> <C name="{../@id}"> <xsl:copy-of select="node()"/> </C> </xsl:template> </xsl:stylesheet> when this transformation is applied on the provided XML document (corrected to be made well-formed):
<A> <B id="x"> <C> <D/> <D/> <D/> <D/> </C> </B> </A> the wanted, correct result is produced:
<C name="x"> <D/> <D/> <D/> <D/> </C> Explanation:
Proper use of template pattern matching.
Use of AVT.
name in result instead of id.I would go for
<?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" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/"> <out> <xsl:apply-templates/> </out> </xsl:template> <xsl:template match="C"> <xsl:copy> <xsl:attribute name="name"><xsl:value-of select="../@id"></xsl:value-of></xsl:attribute> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="A|B"> <xsl:apply-templates/> </xsl:template> </xsl:stylesheet> Which transforms
<?xml version="1.0" encoding="UTF-8"?> <A> <B id="x"> <C> <D/> <D/> <D/> <D/> </C> </B> </A> into
<?xml version="1.0" encoding="UTF-8"?> <out> <C name="x"> <D/> <D/> <D/> <D/> </C> </out>