1

次の XML があります。

<root>
    <book>
        <element2 location="file.txt"/>
        <element3>
            <element3child/>
        </element3>
    </book>
    <book>
        <element2 location="difffile.txt"/>
    </book>
</root>

すべてをコピーできるようにする必要がありますが、 /root/book/element2[@location='whateverfile'] にあるかどうかを確認してください。ここにいる場合は、兄弟要素 3 が存在するかどうかを確認する必要があります。存在しない場合は、<element3>. 一方、すでに存在する場合は、その子要素に移動しlast()、独自の要素を見つけて追加する必要があります<element3child>

これまでのところ、私は次のことを思いつきました。ただし、私は XSLT を初めて使用するので、構文などのヘルプが必要であることを覚えておいてください。

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="/root/book/element2[@location='file.txt']/../*/last()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
    <element3child/>
</xsl:template>
4

1 に答える 1

1
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" />

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

    <!--If an <element2> has an <element3> sibling, 
          then add <element3child> as the last child of <element3> -->
    <xsl:template match="/root/book[element2[@location='file.txt']]
                           /element3/*[position()=last()]">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
        <element3child/>
    </xsl:template>

    <!--If the particular <element2> does not have an <element3> sibling, 
           then create one -->
    <xsl:template match="/root/book[not(element3)]
                           /element2[@location='file.txt']">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
        <element3/>
    </xsl:template>

</xsl:stylesheet>
于 2011-10-14T11:17:08.683 に答える