与XSL

2012-01-27 43 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