I have a xml like follows,
<doc>
<a type="atr111"></a>
<a type="atr111"></a>
<a type="atr111"></a>
<a type="atr222"></a>
<a type="atr222"></a>
<a type="atr222"></a>
</doc>
my requirements are,
- add dynamically increment
id
attribute to nodes which has attributeatr111
andatr222
- add new node inside nodes, named
<newNode>
having attributeid="newAttr"
which has attributeatr111
andatr222
- change
<a>
nodes attribute valueatr111
toatr222
.
so my expected output is,
<doc>
<a id="id-1" type="atr222"><newNode id="newAttr"/></a>
<a id="id-2" type="atr222"><newNode id="newAttr"/></a>
<a id="id-3" type="atr222"><newNode id="newAttr"/></a>
<a id="id-4" type="atr222"><newNode id="newAttr"/></a>
<a id="id-5" type="atr222"><newNode id="newAttr"/></a>
<a id="id-6" type="atr222"><newNode id="newAttr"/></a>
</doc>
the xsl I have written to get those output is follows,
<xsl:template match="a" priority="1">
<!-- add new dynamic id -->
<xsl:copy>
<xsl:attribute name="id">
<xsl:value-of select="'id-'"/>
<xsl:number count="a[@type='atr111' or @type='atr222']" level="any"/>
</xsl:attribute>
</xsl:copy>
<!-- add newNode inside <a> node -->
<xsl:copy>
<newNode>
<xsl:attribute name="id">newAttr</xsl:attribute>
</newNode>
</xsl:copy>
</xsl:template>
<!-- change existing 'atr111' attribute value to 'atr222' -->
<xsl:template match="a/@type[. = 'atr111']">
<xsl:attribute name="type">atr222</xsl:attribute>
</xsl:template>
My current output comes as follows,
<doc>
<a id="id-1"/><a><newNode id="newAttr"/></a>
<a id="id-2"/><a><newNode id="newAttr"/></a>
<a id="id-3"/><a><newNode id="newAttr"/></a>
<a id="id-4"/><a><newNode id="newAttr"/></a>
<a id="id-5"/><a><newNode id="newAttr"/></a>
<a id="id-6"/><a><newNode id="newAttr"/></a>
</doc>
As you can see dynamic ids have added as expected, and <newNode>
with new attribute has also added.but it has duplicated the <a>
node. also existing attribute type
has disappeared.
How can I organize my code to get the expected output?