DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Find And Replace Inside An XML File With XSLT

08.15.2011
| 11994 views |
  • submit to reddit
        // description of your code here
//This XSL will search inside certain nodes of a given XML file
//for certain values and replace them.
//In my example I have a UnitOfMeasure node that contains "EA" or "FT" but I want to change
//the EA to 1 and the FT to 0.
//Also in my ObsoleteIndicator node I want to replace OBS with 1 and this other value I don't care about, 
//DNR to empty string to basically remove it.
//So we end up with the exact same XML we started with just with those values translated.
//You could do the same with regular string.replace but it would be very slow for large XML files
//as it would have to visit every character in the entire file each time you called it (in my case
// four times.)

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

<xsl:template match="//UnitofMeasure">
	<xsl:element
	name="{name(.)}">

		<xsl:choose>
			<xsl:when test="contains(string(.),'EA')">
				<xsl:value-of select="translate(string(.), 'EA', '1')" />
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="translate(string(.), 'FT', '0')" />	
			</xsl:otherwise>
		</xsl:choose>
	
	</xsl:element>
</xsl:template>

<xsl:template match="//ObsoleteIndicator">
	<xsl:element
	name="{name(.)}">
	
		<xsl:choose>
			<xsl:when test="contains(string(.),'OBS')">
				<xsl:value-of select="translate(string(.), 'OBS', '1')" />
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="translate(string(.), 'DNR', '')" />	
			</xsl:otherwise>
		</xsl:choose>
		
	</xsl:element>
</xsl:template>

</xsl:stylesheet>