2015-11-25 86 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>