使用XSLT/XPATH 1.0,我想创建HTML,其中元素的class
属性span
指示原始XML层次结构中的深度.
例如,使用此XML片段:
<text>
<div type="Book" n="3">
<div type="Chapter" n="6">
<div type="Verse" n="12">
</div>
</div>
</div>
</text>
Run Code Online (Sandbox Code Playgroud)
我想要这个HTML:
<span class="level1">Book 3</span>
<span class="level2">Chapter 6</span>
<span class="level3">Verse 12</span>
Run Code Online (Sandbox Code Playgroud)
这些div
元素的深度可以先验地知道.在div
小号可能是书- >章.它们可以是Volume - > Book - > Chapter - > Paragraph - > Line.
我不能依赖@type的值.部分或全部可能为NULL.
Dim*_*hev 17
这有一个非常简单和简短的解决方案 - 没有递归,没有参数,没有xsl:element
,没有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>
Run Code Online (Sandbox Code Playgroud)
当此转换应用于提供的XML文档时:
<text>
<div type="Book" n="3">
<div type="Chapter" n="6">
<div type="Verse" n="12"></div></div></div>
</text>
Run Code Online (Sandbox Code Playgroud)
产生了想要的正确结果:
<span class="level1">Book 3</span>
<span class="level2">Chapter 6</span>
<span class="level3">Verse 12</span>
Run Code Online (Sandbox Code Playgroud)
说明:正确使用模板,AVT和count()
功能.
或者不使用递归 - 但Dimitre的答案比我的更好
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/text">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="//div">
<xsl:variable name="depth" select="count(ancestor::*)"/>
<xsl:if test="$depth > 0">
<xsl:element name="span">
<xsl:attribute name="class">
<xsl:value-of select="concat('level',$depth)"/>
</xsl:attribute>
<xsl:value-of select="concat(@type, ' ' , @n)"/>
</xsl:element>
</xsl:if>
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7622 次 |
最近记录: |