XSL - 如何匹配或选择空元素以插入生成的内容



我正在使用XSLT将XML文件转换为HTML。转换的一部分包括输出导航栏。我有一些代码可以遍历树并获取每个部分的标题并将其输出为列表项。但是,某些类型的部分是空的并完全生成。当这些部分出现时,我需要能够在导航栏中插入默认标题。我正在使用xsl:choose插入标题,但我无法找到在空元素上匹配的方法。

我已经查看了此处提到的其他解决方案,包括my-empty-element[. = '']my-empty-element[not(text())]的测试,但这些对我不起作用。我的 XML 文档的简化版本:

<book>
<section id="s1">
<title>Section 1 Title</title>
<!-- Other stuff here -->
</section>
<section-empty id="s2"/> <!-- My generated section -->
<section id="s3">
<title>Section 3 Title</title>
<!-- Other stuff here -->
</section>
</book>

编辑以添加进一步说明:在本书的常规处理过程中,每个部分都分解为一个单独的文件。在处理每个部分时,我包含<xsl:call-template name="navbar"/>因此导航栏实际上是从该部分调用的。

为了确认,空部分的名称与常规部分的名称不同。下面是我的 XSL 的简化版本:

<xsl:template name="navbar">
<!-- I call this template in at the location of the navbar in my HTML document -->
<xsl:apply-templates select="/book" mode="nav"/>
</xsl:template>
<xsl:template match="/book" mode="nav">
<nav class="mainnav"><ul>
<xsl:apply-templates select="section | section-empty" mode="nav"/>
</ul></nav>
</xsl:template>
<xsl:template match="section | section-empty" mode="nav">
<li><a>
<xsl:attribute name="id"><xsl:value-of select="./@id"/></xsl.attribute>
<xsl:choose>
<xsl:when test="self::section"><xsl:value-of select="./title/text()"/></xsl:when>
<xsl:when test="self::section-empty"><xsl:text>Generated Title</xsl:text></xsl:when>
<xsl:otherwise/>
</xsl:choose>
</a></li>
</xsl:template>

我还尝试创建一个单独的模板来匹配book/section-empty[.='']但这没有任何区别。我当前的输出如下所示:

<nav><ul>
<li><a href="s1">Section 1 Title</a></li>
<li><a href="s3">Section 3 Title</a></li>
</ul</nav>

我感谢任何人可以提供的任何帮助。

编辑为包含原始示例中<xsl:attribute name="id">的关闭标记。

目前尚不清楚为什么您不能直接匹配您说的元素名称:

<xsl:template match="/book" >
<nav class="mainnav"><ul>
<xsl:apply-templates select="section | section-empty" />
</ul></nav>
</xsl:template>
<xsl:template match="section">
<li>
<a href="{@id}">
<xsl:value-of select="title"/>
</a>
</li>
</xsl:template>
<xsl:template match="section-empty">
<li>
<a href="{@id}">Generated Title</a>
</li>
</xsl:template>

https://xsltfiddle.liberty-development.net/3NSTbeV

我的问题是我的模板匹配中元素名称中的拼写错误。我有一个大写字母,小写字母应该是。我在检查我的代码时错过了它。Martin Honnen 确认我的代码应该可以工作,并鼓励使用更好的故障排除示例,这有助于我找到错误。

最新更新