15 Feb 2007

XSLT: Search replace attribute values

Posted by Jacob Emcken

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.

3 Comments to XSLT: Search replace attribute values

Francis Mathew
May 14, 2008

I’m new to XSLT. How do I run the same from a Java program?
I have the following requirements 1) I have to change attribute values using Java – but the resulting file should retain the same format, comments etc. but the values should change. 2) Get a report of (atleast the no of instance) changes in a file 3) Backup the file if there is a change (e.g. with a new extension like .replacedByXXX)

Jørn
April 22, 2010

I have a similar problem, but I can’t seem to find you xslt code in the post.

Jacob Emcken
June 11, 2010

I’m sorry about that.

Wordpress keeps f****** me over when I want to display html and xml. I’ve updated the post so you should be able to figure out whats happening :)

Leave a comment