gpt4 book ai didi

html - 使用 XSL 删除不需要的标签

转载 作者:搜寻专家 更新时间:2023-10-31 08:06:26 25 4
gpt4 key购买 nike

我收到了一些未知的内容作为描述,可能是这样的:

<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。因此,例如, 将被删除,但

将保留。我假设我必须匹配我想要的那些(并确保没有任何东西可以匹配其他的),但不知道如何去做。

有什么帮助吗?

最佳答案

白名单那些元素:

<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 添加到最终模板。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com