XSL复制模板并添加新属性

时间:2014-09-10 10:38:29

标签: xml xslt copy add nodes

输入XML:

<a>
    <b1>
        <c1 width="500" height="200">
            <d1 data="null" />
        </c1>
    </b1>
    <b2 />
</a>

我想复制所有属性从b1/c1b2/c1 AND 添加新属性( length)。 输出XML应为:

<a>
    <b1>
        <c1 width="500" height="200">
            <d1 data="null" />
        </c1>
    </b1>
    <b2>
        <c1 width="500" height="200" length="2">
            <d1 data="null" />
        </c1>
    </b2>
</a>

我有一个代码,复制全部从b1 / c1到b2 / c2但是没有添加新的atttribute(length):

<xsl:template match="/a/b2">
    <xsl:copy>
        <xsl:apply-templates select="@*" />
        <xsl:copy-of select="/a/b1/c1" />
        <xsl:apply-templates select="*" />
    </xsl:copy>
</xsl:template>

我尝试添加属性到副本部分,但它不起作用:

<xsl:template match="/a/b2">
    <xsl:copy>
        <xsl:apply-templates select="@*" />
        <xsl:copy-of select="/a/b1/c1" >
            <xsl:attribute name="length">2</xsl:attribute>
        </xsl:copy-of>
        <xsl:apply-templates select="*" />
    </xsl:copy>
</xsl:template>

2 个答案:

答案 0 :(得分:2)

以身份模板开头,然后覆盖b2节点。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <xsl:strip-space elements="*"/>

    <xsl:output indent="yes"/>

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

    <xsl:template match="b2">
        <xsl:copy>
            <xsl:apply-templates select="../b1/c1" mode="test"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="c1" mode="test">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:attribute name="length">2</xsl:attribute>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

答案 1 :(得分:2)

重新编辑您的问题 - 尝试:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="b2">
    <xsl:copy>
        <xsl:apply-templates select="../b1/c1" mode="copy"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="c1" mode="copy">
    <xsl:copy>
        <xsl:attribute name="length">2</xsl:attribute>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
相关问题