2010-04-23 63 views
3

以下是已有的xml文件。我想知道如何在使用xslt的第一個元素之前插入元素?XSLT插入一次自定義文本

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

我想用for-each循環和測試位置= 0,但在第一次出現的換它的每一個爲時已晚。這是一次性的文本,所以我不能將它與已經在xsl文件中的其他xslt模板結合起來。

謝謝。

+0

+1爲好問題。看到我的答案是一個非常簡短的解決方案。 :) – 2010-04-23 03:16:01

回答

3

你應該知道並記住一件最重要的事情:身份規則

下面是使用最根本的XSLT設計模式非常簡單和緊湊的解決方案:使用並重寫身份規則:

<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>