使用 XSLT 重复元素 x 次数 [英] Duplicate Element x number of times with XSLT

查看:33
本文介绍了使用 XSLT 重复元素 x 次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行一个奇怪的转变.

I have a strange transformation that I'm trying to do.

XML 看起来像这样:

XML looks like this:

<?xml version="1.0" standalone="yes"?>
<Parent>
    <RecordCount>4</RecordCount>
    <Record name="1">
        <Child1>Value 1</Child1>
        <Child2>Value 2</Child2>
    </Record>
</Parent>

这就是它需要的样子:

<?xml version="1.0" standalone="yes"?>
<Parent>
    <RecordCount>4</RecordCount>
    <Record name="1">
        <Child1>Value 1</Child1>
        <Child2>Value 2</Child2>
    </Record>
    <Record name="2">
        <Child1>Value 1</Child1>
        <Child2>Value 2</Child2>
    </Record>
    <Record name="3">
        <Child1>Value 1</Child1>
        <Child2>Value 2</Child2>
    </Record>
    <Record name="4">
        <Child1>Value 1</Child1>
        <Child2>Value 2</Child2>
    </Record>
</Parent>

使用 XSLT 甚至可以实现这样的事情,还是我应该只在代码中处理?

Is something like this even possible with XSLT or should I rather just handle this in code?

推荐答案

这是使用 XSLT 2.0 的另一种方式...

Here's another way using XSLT 2.0...

XML 输入

<Parent>
    <RecordCount>4</RecordCount>
    <Record name="1">
        <Child1>Value 1</Child1>
        <Child2>Value 2</Child2>
    </Record>
</Parent>

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

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

    <xsl:template match="RecordCount">
        <xsl:variable name="record" select="../Record"/>
        <xsl:copy-of select="."/>
        <xsl:for-each select="1 to .">
            <xsl:apply-templates select="$record" mode="replicate">
                <xsl:with-param name="cnt" select="."/>
            </xsl:apply-templates>
        </xsl:for-each>
    </xsl:template>

    <xsl:template match="Record" mode="replicate">
        <xsl:param name="cnt"/>
        <Record name="{$cnt}">
            <xsl:apply-templates select="@* except @name|node()"/>
        </Record>
    </xsl:template>

    <xsl:template match="Record"/>

</xsl:stylesheet>

输出

<Parent>
   <RecordCount>4</RecordCount>
   <Record name="1">
      <Child1>Value 1</Child1>
      <Child2>Value 2</Child2>
   </Record>
   <Record name="2">
      <Child1>Value 1</Child1>
      <Child2>Value 2</Child2>
   </Record>
   <Record name="3">
      <Child1>Value 1</Child1>
      <Child2>Value 2</Child2>
   </Record>
   <Record name="4">
      <Child1>Value 1</Child1>
      <Child2>Value 2</Child2>
   </Record>
</Parent>

这篇关于使用 XSLT 重复元素 x 次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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