XSLT:递归映射 [英] XSLT:Recursive Mapping

查看:36
本文介绍了XSLT:递归映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 XSLT 转换的新手,并被这种递归映射困住了.

I am new to XSLT transformation and got stuck with this recursive mapping.

<Element1>
  <Element11/>
  <Element12/>
  <Element13/>
  <Element1>
     <Element11/>
     <Element12/>
     <Element13/>
  </Element1>
</Element1>

将转化为

<Information>
 <Element11/>
 <Element12/>
 <Element13/>
</Information>
<!-- This will be the child Element1 -->
<Metadata>
 <Element11/>
 <Element12/>
 <Element13/>
</Metadata>

我绝对不能用:

<xsl:template match="/">
            <xsl:for-each select="Element1">
                <Information>
            </xsl:for-each>
    </xsl:template>

推荐答案

这应该可以:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes"/>

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

  <!-- Template handling the top-level 'Element1' -->
  <xsl:template match="Element1">
    <Information>
      <!-- Apply the copy template to all sub-elements except 'Element1' -->
      <xsl:apply-templates select="*[name()!='Element1']"/>
    </Information>
    <!-- Apply the templates to the 'Element1' sub-elements -->
    <xsl:apply-templates select="Element1"/>
  </xsl:template>

  <!-- Template handling the inner 'Element1' -->
  <xsl:template match="Element1/Element1">
    <Metadata>
      <xsl:apply-templates/>
    </Metadata>
  </xsl:template>

</xsl:stylesheet>

正如 Tim 所指出的,结果不是有效的 XML,因为它有两个根元素.要生成额外的 root 元素以使输出有效的 XML,请添加此模板:

As Tim notes the result is not a valid XML because it has two root elements. To generate an extra root element to make the output valid XML add this template:

<xsl:template match="/">
  <root>
    <xsl:apply-templates></xsl:apply-templates>
  </root>
</xsl:template>

这篇关于XSLT:递归映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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