4

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> 

3 Answers 3

5

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:

  1. Proper use of template pattern matching.

  2. Use of AVT.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice compact solution :-) minor issue: attribute name in result instead of id.
0

With . being C:

<xsl:copy> <xsl:attribute name="name"> <xsl:value-of select="../@id"/> </xsl:attribute> <xsl:copy-of select="*"/> </xsl:copy> 

Comments

0

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> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.