[英]<xsl:value-of select=“document(content)//title”/> returns empty node
[英]XSL - How to match or select empty element to insert generated content
我正在使用 XSLT 將 XML 文件轉換為 HTML。 部分轉換包括輸出導航欄。 我有一些代碼遍歷樹並獲取每個部分的標題並將其作為列表項輸出。 但是,某些類型的部分是空的並且是完全生成的。 當這些部分出現時,我需要能夠在導航欄中插入一個默認標題。 我正在使用xsl:choose
插入標題,但我無法找到匹配空元素的方法。
我查看了此處提到的其他解決方案,包括對my-empty-element[. = '']
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>
我的問題是模板匹配中元素名稱的拼寫錯誤。 我有一個大寫字母,小寫字母應該是。 在檢查我的代碼時我錯過了它。 Martin Honnen 確認我的代碼應該可以工作,並鼓勵使用更好的示例進行故障排除,這幫助我找到了我的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.