xslt - 找到章节的最大深度

标签 xslt xslt-2.0 max depth xpath-2.0

大家。在这种情况下,我想计算章节的最大深度。例如,一本没有章节的书的高度为 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

关于xslt - 找到章节的最大深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5972390/

相关文章:

xml - 我需要一个模式规则,仅当另一个属性首先存在时才强制执行该属性的存在。

xslt - XSLT 中的上个月最后一天

xslt - XPath轴与XSLT/Xpath中的位置路径表达式相比,性能更好

ruby-on-rails - maximum in group by 事件记录查询

java - 将参数从 java 嵌入式 fop 传递到 xsl 文件

java - 使用 XSLT 如何以引导加载方式从 XML 获取资源链接?

xslt - 有没有办法在 xsl :if test? 中使用模式

xml - 从命名空间前缀节点中删除 xmlns 属性

ruby-on-rails - Rails 验证中未指定范围

mysql - 使用mysql从表中获取最新记录