1

我有以下 XML:

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

我需要能够复制所有内容,但要检查我们是否在 /root/book/element2[@location='whateverfile'] 中。如果我们在这里,我们需要检查兄弟 element3 是否存在,如果不存在,我们添加一个<element3>. 另一方面,如果它已经存在,我们需要转到它的子元素并找到last()并附加我们自己的元素 say <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 回答