如何使用模板进行复制时在XSLT中创建元素

时间:2010-03-31 18:37:22

标签: xml xslt

我正在尝试在XML中创建一个复制和修改基本内容的元素。

我的XML就像

<root>
  <node>
     <child>value</child>
     <child2>value2</child2>
  </node>
  <node2>bla</node2>
</root>

节点的子节点数可能会与root的子节点一起更改。 XSLT应该复制整个内容,修改一些值添加一些新内容。

复制和修改没问题:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" encoding="UTF-8"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy> 
  </xsl:template>
</xsl:stylesheet>

(+进一步修改模板)。

但是如何在某个路径上添加此结构中的新元素,例如我想添加一个元素作为“节点”节点的最后一个元素。 “node”元素本身始终存在。

1 个答案:

答案 0 :(得分:5)

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" encoding="UTF-8"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy> 
  </xsl:template>
  <xsl:template match="node">
    <node>
      <xsl:apply-templates select="@*|node()"/>
      <newNode/>
    </node> 
  </xsl:template>
</xsl:stylesheet>