xslt - 使用 xslt 将 xml 转换为 html 列表
问题描述
我有一个将 xml 文件转换为 html 列表的 xslt 代码。输入输出样本如下:
输入:
<Beverages>
<Water/>
<Coffee/>
<Tea>
<BlackTea/>
<WhiteTea id="cti" value="ctv" >Camomile Tea</WhiteTea>
<GreenTea id="gti" value="gtv">
<Sencha/>
<Gyokuro/>
<Matcha/>
<PiLoChun/>
</GreenTea>
</Tea>
</Beverages>
和输出:
<ul>
<li>
<span class="caret"><Beverages></span>
<ul class="nested">
<li><span><Water/></span></li>
<li><span><Coffee/></span></li>
<li>
<span class="caret"><Tea></span>
<ul class="nested">
<li><span><BlackTea/></span></li>
<li><span><WhiteTea id="cti" value="ctv"></span>Camomile Tea<span></WhiteTea></span></li>
<li>
<span><GreenTea id="gti" value="gtv"></span>
<ul class="nested">
<li><span><Sencha/></span></li>
<li><span><Gyokuro/></span></li>
<li><span><Matcha/></span></li>
<li><span><PiLoChun/></span></li>
</ul>
<span></GreenTea></span>
</li>
</ul>
</li>
</ul>
<span></Beverages></span>
</li>
</ul>
这是我的 xslt,但它与我想要的不完全相同:
<xsl:template match="/">
<ul><xsl:apply-templates/></ul>
</xsl:template>
<xsl:template match="*">
<li> <span class="caret"><xsl:value-of select="concat('<',name())" />
<xsl:for-each select="@*">
<xsl:value-of select="concat(' ',name())"/>=<xsl:value-of select="concat('"',.,'"')" />
</xsl:for-each>></span>
<xsl:if test="text()">
<xsl:apply-templates select="text()" />
</xsl:if>
<xsl:if test="*">
<ul class="nested"><xsl:apply-templates/></ul>
</xsl:if>
<span><xsl:value-of select="concat('<','/' ,name() , '>')" /></span></li>
</xsl:template>
问题是这段代码无法区分父元素和非父元素。对于父元素,我们需要添加 class="caret" 属性,但对于非父元素,我们不应该添加此类。
解决方案
这应该适合你。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<ul>
<xsl:apply-templates/>
</ul>
</xsl:template>
<xsl:template match="*">
<li>
<span>
<xsl:if test="*">
<xsl:attribute name="class">
<xsl:value-of select="'caret'"/>
</xsl:attribute>
</xsl:if>
<xsl:value-of select="concat('<',name())"/>
<xsl:for-each select="@*">
<xsl:value-of select="concat(' ', name(), '=', '"', ., '"')"/>
</xsl:for-each>
<xsl:choose>
<xsl:when test="text() or *">
<xsl:value-of select="'>'"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'\>'"/>
</xsl:otherwise>
</xsl:choose>
</span>
<xsl:if test="text()">
<xsl:value-of select="text()"/>
</xsl:if>
<xsl:if test="*">
<ul class="nested">
<xsl:apply-templates/>
</ul>
</xsl:if>
<xsl:if test="text() or *">
<span>
<xsl:value-of select="concat('<','/' ,name() , '>')"/>
</span>
</xsl:if>
</li>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- php - 如何以原始函数树枝的形式在我的 var 中取消转义字符串 html?
- java - RecyclerView 在活动中总是空白
- powershell - 如何将 powershell 中文件的 SHA256 哈希值与已知值进行比较?
- hyperlink - 如何正确显示从 Sphinx 文档生成器生成的 pdf 中的超链接
- c# - 我正在尝试从字符串列表中删除空字符串,但奇怪的是并非所有字符串都被删除
- python - 导入torch时文件太短
- python - 蟒蛇 | 实例化之前的类方法装饰器
- java - 如何在 Java 中进行日期格式验证
- android - Android Studio APK Parse Error 解析包时出现问题
- django - Django + Celery + Apache mod_wsgi + Postgres + RabbitMQ 用于多个客户端的应用程序