I want to update some nodes in XML using XSLT. Like contact detail and Email. Currently I am using command like:
<xsl:template match="@*|node()*">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/Metadata/contact/node/Email">
<xsl:variable name="OName" select="/Metadata/contact/organisationName/CharacterString"/>
<xsl:variable name="Email" select="/Metadata/contact/node/Email/CharacterString"/>
<xsl:choose>
<xsl:when test="contains($OName,'TestOrg')">
<CharacterString>
<xsl:value-of select="'[email protected]'"/>
</CharacterString>
</xsl:when>
<xsl:otherwise>
<CharacterString>
<xsl:value-of select="$Email"/>
</CharacterString>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
As Contact nodes are multiple and in each Contact node there are one organizaion name and email id. For ex of contact nodes are 3 and currently it fetch 3 values in $OName variable and $Email variable so nodes are not match. So how can I update only some nodes in xml using XSLT?
The very first template you have is a so called "Identity template" and will loop through your complete source XML:
The second template you have will match on every
/Metadata/contact/node/Email
. I would write this template a little bit different. Instead of matching the absolute path, I think it is best to match theEmail/CharacterString
node and then perform your actions.I would use a template like:
Above template only matches the node you want to change (being
Email/CharacterString
). Once matches thexsl:copy
copies the current selected node (CharacterString
). The value will be filled depending on the value ofancestor::contact/organisationName/CharacterString
. I am using the XPath Axeancestor
overhere. Which will be handy when changing the template.If I would now change the template, for example only select the contact nodes that I would like to change, the second template can be written as:
Here I only apply the template to
contact
nodes where ([]
) theorganisationRole/CharacterString
equals the value 1. Note that the body of the template did not change. Therefore you can see why the use of the XPath Axe is usefull.Complete XSLT
Source XML
Produced output
EDIT
If you only want to change the
Email/CharacterString
from the contacts where theorganisationName/CharacterString
contains the textTestOrg
the XSLT would look like this: