I have an xml tree with a dynamic root element (not a static name) and some children under that root element. Now I want to add to the children an element at the second position with a xslt script. How can I do it?
Example:
xml:
<root>
<element1>
<element1a>
..
</element1a>
</element1>
<element2 name="exampleName">This is text.</element2>
</root>
should be converted to
<root>
<element1>
<element1a>
..
</element1a>
</element1>
<someNewElement>1234</someNewElement>
<element2 name="exampleName">This is text.</element2>
</root>
What I got so far is the following. But with that solution the node is only added at the first position. I need it at the second position.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:template match="/">
<xsl:apply-templates select="/*"/>
</xsl:template>
<xsl:template match="/*">
<xsl:copy>
<xsl:element name="newElement">4711</xsl:element>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
This defines a template that matches the first element child of the document element, does the normal identity template processing (using
next-match) and then inserts your new element following it. You could alternatively doto match the second child and insert the element before it. The difference between the two is apparent if
<root>has only one child element, in which case the/*/*[1]version would insert thenewElementbut the/*/*[2]would not.