XSLT: Search replace attribute values
Yesterday I needed an xsl transformation which could replace a specific attribute value in a xml file and keep the rest intact. The following code is put together by pieces I found around the net (copy-paste FTW :) ):
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="attribute"/>
<xsl:param name="oldvalue"/>
<xsl:param name="newvalue"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- This is a generic search replace of attribute values -->
<xsl:template match="@*" priority="10">
<xsl:attribute name="{name()}">
<xsl:choose>
<xsl:when test="(name()=$attribute) and (. = $oldvalue)"><xsl:value-of select="$newvalue"/></xsl:when>
<xsl:otherwise><xsl:value-of select="."/></xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
Lets say that the above code is saved in a file called attribute_replace.xslt
. Now with xsltproc
you would be able to replace the vaule 5011
with 5015
in all attributes called port
:
xsltproc --stringparam attribute port --stringparam oldvalue 5011 --stringparam newvalue 5015 attribute_replace.xslt server_config.xml > new_server_config.xml
I used this to manupulate with some JBoss configuration files.
XSLT: Search replace attribute values
© 2007 by Jacob Emcken is licensed under CC BY-SA 4.0