【问题标题】:XSLT add node if node does not exist, append child if it doesXSLT 如果节点不存在则添加节点,如果存在则追加子节点
【发布时间】:2011-10-14 10:20:28
【问题描述】:

我有以下 XML:

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

我需要能够复制所有内容,但要检查我们是否在 /root/book/element2[@location='whateverfile'] 中。如果我们在这里,我们需要检查兄弟 element3 是否存在,如果不存在,我们添加&lt;element3&gt;。另一方面,如果它已经存在,我们需要转到它的子元素并找到 last() 并附加一个我们自己的元素,比如 &lt;element3child&gt;

到目前为止,我想出了以下内容。但请记住,我是 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>

【问题讨论】:

    标签: xslt copy insertion


    【解决方案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>
    

    【讨论】:

    • 感谢您的帮助。完美运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多