XSLT插入一次性自定义文本。

3
以下是现有的XML文件。我想知道如何使用XSLT在第一个<book>元素之前插入一个<new_element>元素?
<XmlFile>
    <!-- insert another <tag> element here -->
    <tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
    <tag>
        <innerTag>
        </innerTag>
    </tag>
</XmlFile>

我考虑使用for-each循环并测试position = 0,但在第一次出现for-each时就已经太迟了。这是一次性文本,因此我无法将其与已经存在于xsl文件中的其他xslt模板合并。

谢谢。


+1 鼓励这个好问题。请看我的答案,提供一种非常简短和易于使用的解决方案。 :) - Dimitre Novatchev
1个回答

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接