找到章节的最大深度

2024-01-08

每个人 。在这种情况下,我想计算章节的最大深度。例如,一本没有章节的书的高度为 0 。一本书只有章节没有章节,高度应该为1。以下是xml:

<book title="D">
<author>
  <name>abc</name>
</author>

<chapter title="chapter1">
  <section title="section1.1"/>
  <section title="section1.2">
    <section title="section1.2.1"/>
<section title="section1.2.2"/>
  </section>
  <section title="section1.3">
<section title="section1.3.1"/>
  </section>
</chapter>

<chapter title="chapter2"/>

</book>

顺便说一下,我用的是撒克逊语。我想尝试仅使用匹配模板。在这种情况下,输出是文本,结果是

 3

这是我用于计算每个音符深度的 XSL?是吗?那么如何通过调用名为 max 的模板来输出电流的最大值呢?

<xsl:transform version="2.0"
           xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/">
    <xsl:apply-templates select="book"/>
    <xsl:text>&#10;</xsl:text>
</xsl:template>

<xsl:template match="book">
    <xsl:apply-templates select="chapter">
        <xsl:with-param name ="depth" select ="1"/>
    </xsl:apply-templates>
</xsl:template>

<xsl:template match="chapter|section">
    <xsl:param name="depth"  as="item()*"/>
    <xsl:variable name ="current" select ="$depth"/>
    <xsl:sequence select ="$depth"/>
    <xsl:if test ="not(empty(section))">
        <xsl:apply-templates select="section">
            <xsl:with-param name="depth" select="$depth+1"/>
        </xsl:apply-templates>

    </xsl:if>
 </xsl:template>
</xsl:transform >

XSLT 1.0 解决方案:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/">
     <xsl:apply-templates select="//*[self::chapter or self::section]">
       <xsl:sort data-type="number" order="descending" select=
        "count(ancestor::*[self::chapter or self::section])
        "/>
     </xsl:apply-templates>
 </xsl:template>

 <xsl:template match="chapter|section">
    <xsl:if test="position()=1">
     <xsl:value-of select=
     "count(ancestor::*[self::chapter or self::section]) +1
     "/>
    </xsl:if>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时:

<book title="D">
    <author>
        <name>abc</name>
    </author>
    <chapter title="chapter1">
        <section title="section1.1"/>
        <section title="section1.2">
            <section title="section1.2.1"/>
            <section title="section1.2.2"/></section>
        <section title="section1.3">
            <section title="section1.3.1"/></section>
    </chapter>
    <chapter title="chapter2"/>
</book>

产生了想要的正确答案:

3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

找到章节的最大深度 的相关文章

随机推荐