输出层次结构中当前节点的深度 [英] Outputting depth of current node in the hierarchy

查看:22
本文介绍了输出层次结构中当前节点的深度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 XSLT/XPATH 1.0,我想创建 HTML,其中 span 元素的 class 属性指示原始 XML 层次结构中的深度.

例如,使用这个 XML 片段:

<div type="Book" n="3"><div type="Chapter" n="6"><div type="Verse" n="12">

我想要这个 HTML:

第三册<span class="level2">第6章</span><span class="level3">第 12 节</span>

这些 div 元素可以走多深是先验未知的.div 可以是 Book -> Chapter.它们可以是 Volume -> Book -> Chapter -> Paragraph -> Line.

我不能依赖@type 的值.部分或全部可能是 NULL.

解决方案

这有一个非常简单和简短的解决方案——没有递归,没有参数,没有 xsl:element,没有 <代码>xsl:属性:

<xsl:output omit-xml-declaration="yes" indent="yes"/><xsl:strip-space elements="*"/><xsl:template match="div"><span class="level{count(ancestor::*)}"><xsl:value-of select="concat(@type, ' ', @n)"/></span><xsl:apply-templates/></xsl:模板></xsl:stylesheet>

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

<div type="Book" n="3"><div type="Chapter" n="6"><div type="Verse" n="12"></div></div></div>

产生想要的、正确的结果:

第三册<span class="level2">第6章</span><span class="level3">第 12 节</span>

说明:正确使用模板、AVT 和 count() 函数.

Using XSLT/XPATH 1.0, I want to create HTML where the class attribute of a span element indicates the depth in the original XML hierarchy.

For example, with this XML fragment:

<text>
    <div type="Book" n="3">
        <div type="Chapter" n="6">
            <div type="Verse" n="12">
            </div>
        </div>
    </div>
</text>

I want this HTML:

<span class="level1">Book 3</span>
<span class="level2">Chapter 6</span>
<span class="level3">Verse 12</span>

How deep these div elements could go is not known a priori. The divs could be Book -> Chapter. They could be Volume -> Book -> Chapter -> Paragraph -> Line.

I cannot rely on the values of @type. Some or all could be NULLs.

解决方案

This has a very simple and short solution -- no recursion, no parameters, no xsl:element, no xsl:attribute:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="div">
  <span class="level{count(ancestor::*)}">
   <xsl:value-of select="concat(@type, ' ', @n)"/>
  </span>
  <xsl:apply-templates/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

<text>
    <div type="Book" n="3">
        <div type="Chapter" n="6">
            <div type="Verse" n="12"></div></div></div>
</text>

the wanted, correct result is produced:

<span class="level1">Book 3</span>
<span class="level2">Chapter 6</span>
<span class="level3">Verse 12</span>

Explanation: Proper use of templates, AVT and the count() function.

这篇关于输出层次结构中当前节点的深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆