Skip to content

Instantly share code, notes, and snippets.

@cpburnz
Last active May 19, 2016 13:31
Show Gist options
  • Save cpburnz/e11fa0b792e81ee071d443b64e06516f to your computer and use it in GitHub Desktop.
Save cpburnz/e11fa0b792e81ee071d443b64e06516f to your computer and use it in GitHub Desktop.
Update Attribute in Elements using XSLT
<?xml version="1.0"?>
<root>
<parent>
<child id="a" value="true"/>
<child id="b" value="true"/>
<child id="c" value="true"/>
</parent>
</root>
<?xml version="1.0"?>
<root>
<parent>
<child id="a" value="false"/>
<child id="b" value="null"/>
<child id="c" value="true"/>
</parent>
</root>
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common">
<!-- Update the specified children. -->
<xsl:variable name="update">
<child id="a" value="false"/>
<child id="b" value="null"/>
</xsl:variable>
<!-- Match "value" attribute. -->
<xsl:template match="/root/parent/child/@value">
<!-- Get child ID. -->
<xsl:variable name="id" select="current()/parent::node()/@id"/>
<!-- Get matching update. -->
<xsl:variable name="match" select="exsl:node-set($update)/*[@id = $id]"/>
<!-- If there is a match, update value; otherwise, keep value. -->
<xsl:choose>
<xsl:when test="$match">
<xsl:attribute name="{name()}">
<xsl:value-of select="$match/@value"/>
</xsl:attribute>
</xsl:when>
<xsl:otherwise>
<xsl:copy/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Copy all nodes and attributes unless another rule indicates otherwise. -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

XSLT Update Attribute in Elements

Transform XML document:

xsltproc -o output.xml update-attribute.xslt input.xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment