與XSL

2012-01-27 40 views
4

刪除不需要的標籤我有一些未知的內容來作爲說明,或許是這樣的:與XSL

<description> 
    <p> 
    <span> 
     <font>Hello</font> 
    </span> 
    World! 
    <a href="/index">Home</a> 
    </p> 
</description> 

有可能想到的是所有的HTML標籤。我不想要所有的標籤。我想要允許的標籤是p,i,em,strong,b,ol,ul,li和a。因此,例如,< font>將被剝離,但<和> <將>保留。我假設我必須匹配我想要的(並確保沒有什麼與其他人匹配),但無法解決如何去做。

任何幫助?

回答

7

白名單這些元素:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output omit-xml-declaration="yes" indent="yes"/> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="*[not(self::description or self::p or self::i or 
           self::em or self::strong or self::b or 
           self::ol or self::ul or self::li or self::a)]"/> 
</xsl:stylesheet> 

注意,這將刪除不需要的元素和它們下面什麼。到剛剛剝離font元件本身,例如,但允許其孩子,修改最後一個模板是這樣的:

<xsl:template match="*[not(self::description or self::p or self::i or 
          self::em or self::strong or self::b or 
          self::ol or self::ul or self::li or self::a)]"/> 
    <xsl:apply-templates/> 
</xsl:template> 

的等效(和略清潔器)溶液:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output omit-xml-declaration="yes" indent="yes"/> 
    <xsl:template match="@*|node()" priority="-3"> 
     <xsl:copy/> 
    </xsl:template> 
    <xsl:template match="description|p|i|em|strong|b|ol|ul|li|a"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="*"/> 
</xsl:stylesheet> 

相反的方法是到黑名單的不需要的元素:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output omit-xml-declaration="yes" indent="yes"/> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="font|span"/> 
</xsl:stylesheet> 

再次,添加apply-templates到如果你想允許跳過的元素的孩子,最終的模板。

+2

+1好答案。您可以簡化很多白名單...將您的身份模板的匹配屬性更改爲'「description | p | i | ...」'。然後將空模板的匹配屬性更改爲'「*」',並使用'priority =「 - 3」'來確保它位於後座。 – LarsH 2012-01-27 23:38:47

+1

@LarsH - 我只是更新顯示,作爲替代:)不知道爲什麼我原本不這樣做。 – 2012-01-27 23:39:53

+0

@LarsH - 與建議略有不同,因爲它實際上是身份模板,應該退後一步。 – 2012-01-27 23:46:15