开发者

Height of a Table of Contents: finding maximum depth of a node

The height of the chapters and sections can be computed separately. Use matching templates only. This is the input:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE book SYSTEM "book.dtd">
<book title="Definitive XML Schema">
    <author first="Priscilla" last="Walmsley"/>
    <chapter title="A">
        <section title="d"/>
        <section title="g">
            <section title="s"/>
            <section title="t"/>
        </section>
        <section title="e">开发者_如何学Python;
            <section title="f"/>
        </section>
    </chapter>
    <chapter title="B">
        <section title="n"/>
        <section title="c">
            <section title="a"/>
            <section title="m"/>
        </section>
    </chapter>
</book>

the out put is:

 3

which is the maximum depth of a section node


If you want to compute the maximum depth of a section node, than you can use the following XSLT:

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

    <xsl:output method="text"/>

    <xsl:template match="book">
        <xsl:for-each select="//section">
            <xsl:sort select="count( ancestor::node() )" 
                data-type="number" order="descending"/>
            <xsl:if test="position() = 1">
                <xsl:value-of select="count( ancestor::node() ) - 1"/>
            </xsl:if>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

which, given the example XML as imput, will produce the following output:

3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜