如何删除xml标记并将其放在另一个标记中?

时间:2014-07-15 15:04:48

标签: xml xslt

我有一个xml文件,如下所示。

<note>
<from> </from>
<to>
    <name> </name>
    <number> </number>
</to>
<message>
    <head> </head>
    <body> </body>
</message>
</note>

我想使用XSTL构建如下的xml结构。

<note>
<from> </from>

<message>
    <name> </name>
    <number> </number>
    <head> </head>
    <body> </body>
</message>
</note>

我尝试过这样的事情。

<xsl:template match="//to">
  <xsl:copy-of select="//message"/>
</xsl:template>

提前致谢。

1 个答案:

答案 0 :(得分:3)

从身份模板开始,身份模板自己将节点复制到输出文档&#34;原样&#34;

<xsl:template match="@*|node()">
   <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

这意味着您只需要为希望实际更改的节点编写模板。

首先,您不希望 出现在输出中的同一位置,因此请添加模板以忽略它

<xsl:template match="to" />

接下来,您要转换消息元素,以将的子元素追加到元素。您可以使用以下模板执行此操作,该模板类似于标识模板,但需要额外的行来执行额外复制。

<xsl:template match="message">
   <xsl:copy>
     <xsl:apply-templates select="@*|node()"/>
     <xsl:apply-templates select="../to/*"/>
  </xsl:copy>
</xsl:template>

试试这个XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="to" />

  <xsl:template match="message">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <xsl:apply-templates select="../to/*"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
相关问题