Insert XSLT after custom text dropdown

The following is an existing xml file. I was wondering how can I insert an element before the first element using xslt?

<XmlFile>
    <!-- insert another <tag> element here -->
    <tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
</XmlFile>

I thought of using a for-each loop and checking the position = 0, but when for-each first appears, it's too late. This is a one-time text, so I cannot combine it with other xslt templates that are already in the xsl file.

Thank.

+3
source share
1 answer

You need to know and remember one most important thing: the rule of identity .

Here is a very simple and compact solution using the most fundamental XSLT design pattern: using and overriding the identity rule:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

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

 <xsl:template match="/*/*[1]">
   <someNewElement/>
   <xsl:call-template name="identity"/>
 </xsl:template>
</xsl:stylesheet>

XML-, :

<XmlFile>
    <!-- insert another <tag> element here -->
    <someNewElement />
<tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
</XmlFile>
+3

Source: https://habr.com/ru/post/1742378/


All Articles