My project needs to convert xml to rename tag which have the same name as other tag on same level. I try to use the function docucment.renameNode(), but it seems not working... The difficulty is how identify the correct tag to rename.
Exemple, here the source xml :
<A>
<B>
<C></C>
</B>
<B>
<D>
<E></E>
</D>
</B>
<B>
<F></F>
</B>
</A>
Here the new expected xml :
<A>
<B_1>
<C></C>
</B_1>
<B_2>
<D>
<E></E>
</D>
</B_2>
<B_3>
<F></F>
</B_3>
</A>
CodePudding user response:
I wonder why you want to do this conversion: Putting sequence numbers into tag names is generally considered a bad idea, since it usually makes the XML harder to process subsequently.
But if you really want to do it, it's a very straightforward XSLT transformation. In XSLT 3.0 it's
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="B">
<xsl:element name="B_{count(preceding-sibling::B) 1}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:transform>
It's also easy enough with XSLT 1.0, just a few more lines of code to add an identity template in place of the xsl:mode declaration. Still a lot easier than hand-coding it in Java.