I’m looking for a simpler, more elegant way to replace text in XML. For a source XML like:
<A>
<B>
<Name>ThisOne</Name>
<Target>abc</Target>
</B>
<B>
<Name>NotThisOne</Name>
<Target>abc</Target>
</B>
<B>
<Name>ThisOne</Name>
<Target>def</Target>
</B>
</A>
I want to change the text of all Target elements that have the Name of “ThisOne” to “xyz”.
The result would be:
<A>
<B>
<Name>ThisOne</Name>
<Target>xyz</Target> <-- Changed.
</B>
<B>
<Name>NotThisOne</Name>
<Target>abc</Target>
</B>
<B>
<Name>ThisOne</Name>
<Target>xyz</Target> <-- Changed.
</B>
</A>
I accomplished this with:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="B/Target">
<xsl:choose>
<xsl:when test="../Name/text()='ThisOne'"><Target>xyz</Target></xsl:when>
<xsl:otherwise><Target><xsl:value-of select="text()"/></Target></xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
I was thinking this could be done with <xsl:template match=”B/Target/text()”>, so I could just replace the text and not the whole element, but I couldn’t figure out the rest.
Thanks in advance.
This stylesheet:
using your XML input produces: