使用模板复制时如何在 XSLT 中创建元素 [英] How to Create Element in XSLT When Copying Using Templates

查看:22
本文介绍了使用模板复制时如何在 XSLT 中创建元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 XML 中创建一个元素,其中复制和修改了基本内容.

I'm trying to create an element in an XML where the basic content is copied and modified.

我的 XML 类似于

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

节点的子节点数可能会发生变化,根的子节点也会发生变化.XSLT 应该复制整个内容,修改一些值添加一些新值.

The number of children of node may change as well as the children of root. The XSLT should copy the whole content, modify some values and add some new.

复制修改没问题:

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

(+ 进一步的修改模板).

(+ further templates for modifications).

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

But how do I add a new element in this structure on some path, e.g. I want to add an element as the last element of the "node" node. The "node" element itself always exists.

推荐答案

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

这篇关于使用模板复制时如何在 XSLT 中创建元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆