XSLT: copy XML with some minor changes

Today I worked on an XSLT style which copies XML into the same XML but with couple of changes. There were hundreds of elements so I created the following XSLT (example):

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<xsl:template match="/">
		<xsl:for-each select="*">
			<xsl:call-template name="copyElement"/>
		</xsl:for-each>
	</xsl:template>

	<xsl:template name="copyElement">
		<xsl:variable name="segName" select="name(.)" />
		<xsl:element name="{$segName}">
			<xsl:for-each select="@*">
				<xsl:attribute name="{name(.)}">
					<xsl:value-of select="."/>
				</xsl:attribute>
			</xsl:for-each>

			<xsl:choose>
				<xsl:when test="contains($segName, 'SegmentName')">
					<!-- custom code -->
				</xsl:when>
			</xsl:choose>


			<xsl:if test="normalize-space(text()) != ''">
				<xsl:value-of select="normalize-space(.)"/>
			</xsl:if>

			<xsl:for-each select="*">
				<xsl:call-template name="copyElement"/>
			</xsl:for-each>
		</xsl:element>
	</xsl:template>
</xsl:stylesheet>

Gennady Kim

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s