2015-11-25 92 views
1

我正在將XML從XML轉換爲HTML,並且我只希望包含特定元素的段落顯示出來。我該怎麼做呢?XSLT:顯示包含特定子元素的所有元素(並且僅包含那些元素)

我的XML看起來是這樣的:

<?xml version="1.0" encoding="UTF-8"?> 
<text> 
<p>This paragraph contains the <bingo>information</bingo> I want</p> 
<p>This paragraph doesn't.</p> 
<p>This paragraph doesn't</p> 
<p>This paragraph contains the <nest><bingo>information</bingo></nest> I want, too</p> 
<p>This paragraph doesn't</p> 
</text> 

所以我想輸出HTML只包含像第一和第四段落。

到目前爲止,我已經得到了這個。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:template match="/"> 
    <html> 
     <body> 
      <h1>Bingo</h1> 
      <div id="results"> 
       <xsl:for-each select="/text/p"> 
        <xsl:if test="//bingo"> 
         <p> 
          <xsl:value-of select="."/> 
         </p> 
        </xsl:if> 
       </xsl:for-each> 
      </div> 
     </body> 
    </html> 
</xsl:template> 

這顯然是完全錯誤。但我不知道我該怎麼想。我會很感激任何幫助。

回答

1

如果你只需要選擇其中有bingo後裔p元素,那麼你想表達的是這樣的:

<xsl:for-each select="text/p[descendant::bingo]"> 

這也可以寫成這樣...

<xsl:for-each select="text/p[.//bingo]"> 

試試這個XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:template match="/"> 
    <html> 
     <body> 
      <h1>Bingo</h1> 
      <div id="results"> 
       <xsl:for-each select="text/p[.//bingo]"> 
        <p> 
         <xsl:value-of select="."/> 
        </p> 
       </xsl:for-each> 
      </div> 
     </body> 
    </html> 
</xsl:template> 
</xsl:stylesheet> 
0

用模板規則做它,沒有噸,循環和條件:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
<xsl:template match="/"> 
    <html> 
     <body> 
      <h1>Bingo</h1> 
      <div id="results"> 
       <xsl:apply-templates> 
      </div> 
     </body> 
    </html> 
</xsl:template> 

<xsl:template match="p[.//bingo]"> 
    <p><xsl:value-of select="."/></p> 
</xsl:template> 

<xsl:template match="p"/> 

</xsl:stylesheet> 
0

所以我想,只有包含像第一 和第四

段落HTML輸出只需使用此

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

    <xsl:template match="/*"> 
    <html> 
     <body> 
      <h1>Bingo</h1> 
      <div id="results"> 
       <xsl:copy-of select="p[.//bingo]"/> 
      </div> 
     </body> 
    </html> 
    </xsl:template> 
</xsl:stylesheet> 
相關問題