XSLT - 将新节点添加到给定位置

时间:2015-07-24 07:52:05

标签: xml xslt xslt-2.0

我有一个像xml一样的xml,

<doc>
<footnote>
    <p type="Foot">
        <link ref="http://www.facebook.com"/>
        <c>content</c>
        <d>cnotent</d>
    </p>
    <p type="Foot">
        <link ref="http://www.google.com"/>
        <c>content</c>
        <d>cnotent</d>
    </p>
</footnote>
</doc>

我的要求是,

1)向<p>节点添加动态ID,该节点具有属性type="Foot"

2)在<newNode>节点

中添加名为<p>的新节点

3)将动态ID添加到&lt; newNode>

所以输出sholud是

<doc>
<footnote>
    <p id="ref-1" type="Foot">
        <newNode type="direct" refId="foot-1"/>
        <link ref="http://www.facebook.com"/>
        <c>content</c>
        <d>cntent</d>
    </p>
    <p id="ref-2" type="Foot">
        <newNode type="direct" refId="foot-2"/>
        <link ref="http://www.google.com"/>
        <c>content</c>
        <d>cotent</d>
    </p>
</footnote>
</doc>

我写了以下xsl来做那个

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

    <!-- add new dynamic attribute to <p> -->
    <xsl:template match="p[@type='Foot']">
        <xsl:copy>
            <xsl:attribute name="id">
                <xsl:value-of select="'ref-'"/> 
                <xsl:number count="p[@type='Foot']" level="any"/>
            </xsl:attribute>

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

            <!-- add new node with dynamic attribute -->
            <newNode type="direct">
                <xsl:attribute name="refId">
                    <xsl:value-of select="'foot-'"/>
                    <xsl:number count="p[@type='Foot']" level="any"></xsl:number>
                </xsl:attribute>
            </newNode>
        </xsl:copy>

    </xsl:template>

我的问题是在<p>节点内添加新节点广告最后一个节点(如下所示),我需要将其添加为<p>节点内的第一个节点

      <p id="ref-1" type="Foot">
            <link ref="http://www.facebook.com"/>
            <c>content</c>
            <d>cntent</d>
            <newNode type="direct" refId="foot-1"/>
        </p>

如何将第一个节点放在<p>节点内,如下所示?

    <p id="ref-1" type="Foot">
        <newNode type="direct" refId="foot-1"/>
        <link ref="http://www.facebook.com"/>
        <c>content</c>
        <d>cntent</d>
    </p>

1 个答案:

答案 0 :(得分:1)

您需要确保在创建新节点后复制子元素:

<xsl:template match="p[@type='Foot']">
    <xsl:copy>
        <xsl:attribute name="id">
            <xsl:value-of select="'ref-'"/> 
            <xsl:number count="p[@type='Foot']" level="any"/>
        </xsl:attribute>

        <xsl:apply-templates select="@*" />

        <!-- add new node with dynamic attribute -->
        <newNode type="direct">
            <xsl:attribute name="refId">
                <xsl:value-of select="'foot-'"/>
                <xsl:number count="p[@type='Foot']" level="any"></xsl:number>
            </xsl:attribute>
        </newNode>

        <xsl:apply-templates/>
    </xsl:copy>

</xsl:template>
相关问题