Sunday, 21 September 2014

How to replace the nodes based on attribute using xslt



Below is the input xml: Below xml contains cases which is have individual transactions, these transactions need to be replaced with newNode transactions based on attribute of id(id generated unique)



<?xml version="1.0" encoding="UTF-8"?>
<DST>
<CDGCreateTree>
<DST>
<currentJobName>PQContactComplete</currentJobName>
<AWD>
<case>
<transaction relate="Y" id="6745635345346567567567-T01"/>
</case>
<case>
<transaction>
<UIID>Test</UIID>
</transaction>
</case>
</AWD>
</DST>
</CDGCreateTree>
<newNode>
<transaction relate="Y" id="456567535646674524345-TSY"/>
</newNode>
</DST>

My requirement is like second case transaction need to be replaced with newNode transaction by the checking condition like (//transaction[ancestor::*[name() = "CDGCreateTree"]][not(@id)])[1].

Expected Result:

<?xml version="1.0" encoding="UTF-8"?>
<DST>
<CDGCreateTree>
<DST>
<currentJobName>PQContactComplete</currentJobName>
<AWD>
<case>
<transaction relate="Y" id="6745635345346567567567-T01"/>
</case>
<case>
<transaction relate="Y" id="456567535646674524345-TSY"/>
</case>
</AWD>
</DST>
</CDGCreateTree>

</DST>


I have tried below XSLT, But it is not helped me, Please any one suggest me on this.



<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://ift.tt/tCZ8VR" version = "1.0">

<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>

<xsl:variable name="targetNode" select="//newNode/transaction"/>

<xsl:template match="(//transaction[ancestor::*[name() = "CDGCreateTree"]][not(@id)])[1]">
<xsl:copy-of select="$targetNode"/>
</xsl:template>
</xsl:stylesheet>

No comments:

Post a Comment