I am somewhat new to XSLT, and I have a situation where depending on certain conditions I want to convert XML like:

<SomeElement>
<ChildElement/>
<ChildElement/>
<ChildElement/>
...
</SomeElement>

to:

<SomeElement value="something">
<ChildElement/>
<ChildElement/>
<ChildElement/>
...
</SomeElement>


I don't want to specify the child elements in the template that modifies the element, as these may change.

What kind of template with perform this type of transformation?

Recommended Answers

All 2 Replies

Using this input document.

<SomeElement>
	<ChildElement/>
	<ChildElement/>
	<ChildElement/>
</SomeElement>

This transformation produces the result you want.

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

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

	<xsl:template match="SomeElement">
		<xsl:copy>
			<xsl:attribute name="value">
				<xsl:value-of select="'something'"/>
			</xsl:attribute>
			<xsl:apply-templates select="@*"/>
			<xsl:apply-templates select="node()"/>
		</xsl:copy>
	</xsl:template>
</xsl:stylesheet>

The first template is the "identity" template. It takes your input document and copies it completely. The second template is the template for the "SomeElement" element. Once I match on that, I copy the element itself, then create an attribute with a text value of 'something'. Then I apply the identity template on all the children/attributes of SomeElement to produce the rest of the tree.

Result

<SomeElement value="something">
	<ChildElement/>
	<ChildElement/>
	<ChildElement/>
</SomeElement>

Thanks iceandrews,

I was able to get my transform to work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.