0

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?

2
Contributors
2
Replies
4
Views
7 Years
Discussion Span
Last Post by tron_thomas
0

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>
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.