I have a requirement to create XML nodes from XPATH and merge that to the existing XML. I am facing an issue where even if I am specifying the newly generated xml nodes from xpath should be in a specific position of an array it is still coming as the top element of that array. Kindly help to address this issue.
Input XML (here data is an array):
<?xml version="1.0" encoding="UTF-8"?>
<header>
<identifier>12345</identifier>
</header>
<data>
<txCtry>SG</txCtry>
</data>
<data>
<txCtry>TH</txCtry>
</data>
<data>
<txCtry>MY</txCtry>
</data>
XSLT:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all"
xmlns:my="http://example.com/my-functions"
expand-text="yes">
<xsl:output omit-xml-declaration="yes" />
<xsl:variable name="vPop" as="element()*">
<item path="/data[2]/txCurr">MYD</item>
</xsl:variable>
<xsl:variable name="new-nodes">
<xsl:sequence select="my:subTree($vPop/@path/concat(.,'/',string(..)))"/>
</xsl:variable>
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/" name="xsl:initial-template">
<xsl:sequence select="my:merge(*, $new-nodes/*)"/>
</xsl:template>
<xsl:function name="my:merge" as="node()*">
<xsl:param name="node1" as="node()*"/>
<xsl:param name="node2" as="node()*"/>
<xsl:for-each-group select="$node1, $node2" group-by="path()">
<xsl:copy>
<xsl:sequence select="my:merge(@*, current-group()[2]/@*)"/>
<xsl:sequence select="my:merge(node(), current-group()[2]/node())"/>
</xsl:copy>
</xsl:for-each-group>
</xsl:function>
<xsl:function name="my:subTree" as="node()*">
<xsl:param name="pPaths" as="xs:string*"/>
<xsl:for-each-group select="$pPaths"
group-by=
"substring-before(substring-after(concat(., '/'), '/'), '/')">
<xsl:if test="current-grouping-key()">
<xsl:choose>
<xsl:when test=
"substring-after(current-group()[1], current-grouping-key())">
<xsl:element name=
"{substring-before(concat(current-grouping-key(), '['), '[')}">
<xsl:sequence select=
"my:subTree(for $s in current-group()
return
concat('/',substring-after(substring($s, 2),'/'))
)
"/>
</xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="current-grouping-key()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:for-each-group>
</xsl:function>
</xsl:stylesheet>
output XML (Here txCurr as per the XSLT should have been created and added to 2nd position of data array but got added in 0th position):
<header>
<identifier>12345</identifier>
</header>
<data>
<txCtry>SG</txCtry>
<txCurr>MYD</txCurr>
</data>
<data>
<txCtry>TH</txCtry>
</data>
<data>
<txCtry>MY</txCtry>
</data>