The folloiwng is a pre-existing xml file. I was wondering how can I insert a element before the first element using xslt?
<XmlFile>
    <!-- insert another <tag> element here -->
    <tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <inne开发者_如何学CrTag>
        </innerTag>
    </tag>
</XmlFile>
I was thinking of using a for-each loop and test the position = 0, but upon the first occurence of the for-each its already too late. This is a once-off text so I can't combine it with other xslt templates that are already inside the xsl file.
Thanks.
You should know and remember one most important thing: the identity rule.
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>
When this transformation is applied on the provided XML document, the wanted result is produced:
<XmlFile>
    <!-- insert another <tag> element here -->
    <someNewElement />
<tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
</XmlFile>
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论