Is there a way I can update the value of an element base on the value of its attribute?
I use below xslt but it is replacing the value of attribute instead of the value of the element.
INPUT XML:
<Elements>
<Element>
<Entry1>
<data attribute="Delete">value</data>
</Entry1>
<Entry2 attribute="Delete"/>
<Entry3>
<data attribute="Update">value</data>
</Entry3>
</Element>
<Element attribute="Update">
<Entry1>
<data2>
<data3 attribute="Delete">value</data3>
</data2>
</Entry1>
</Element>
<Element attribute="Update">
<Entry1>
<data attribute="Delete">value</data>
</Entry1>
</Element>
</Elements>
XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@attribute">
<xsl:attribute name="attribute">
<xsl:choose>
<xsl:when test=". = 'Delete'">REMOVED</xsl:when>
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
OUTPUT produced by XSLT:
<Elements>
<Element>
<Entry1>
<data attribute="REMOVED">value</data>
</Entry1>
<Entry2 attribute="REMOVED"/>
<Entry3>
<data attribute="Update">value</data>
</Entry3>
</Element>
<Element attribute="Update">
<Entry1>
<data2>
<data3 attribute="REMOVED">value</data3>
</data2>
</Entry1>
</Element>
<Element attribute="Update">
<Entry1>
<data attribute="REMOVED">value</data>
</Entry1>
</Element>
</Elements>
DESIRED OUTPUT:
<Elements>
<Element>
<Entry1>
<data attribute="Delete">REMOVED</data>
</Entry1>
<Entry2 attribute="Delete"/>
<Entry3>
<data attribute="Update">value</data>
</Entry3>
</Element>
<Element attribute="Update">
<Entry1>
<data2>
<data3 attribute="Delete">REMOVED</data3>
</data2>
</Entry1>
</Element>
<Element attribute="Update">
<Entry1>
<data attribute="Delete">REMOVED</data>
</Entry1>
</Element>
</Elements>
CodePudding user response:
Change your main template to
<xsl:template match="*[@attribute='Delete' and normalize-space(.)]">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:text>REMOVED</xsl:text>
</xsl:copy>
</xsl:template>
This replaces the values of all elements with an attribute
attribute which have the value "Deleted" and whose element value is not empty.