XSLT:如何从源中丢弃不需要的 HTML 节点?

XSLT: How to discard unwanted HTML nodes from source?

我正在使用 XSLT 1.0,并在 OS X Yosemite 上使用 xsltproc。 源内容为HTML;目标内容是 XML.

这个问题相当普遍。我要全部 "uninteresting" 节点只是从输出中丢弃。我见过万能的 像这样的指令:

<xsl:template match="node()|script"/>

<xsl:template match="*">
  <xsl:apply-templates/>
</xsl:template>

这接近我需要的。但不幸的是,当我需要添加另一个模板来访问 node() 捕获的文本节点之一时,它太强大了。例如,假设我添加了这个模板:

<xsl:template match="a/div[@class='location']/br">
  <xsl:text> </xsl:text>
</xsl:template>

它只是将某些
元素替换为空格。 好吧,node() 阻止后一个模板生效, 因为包含换行符的相关文本节点被丢弃 已经!

好吧,为了更正这个问题,我用下面的方法代替了包罗万象 node():

<xsl:template match="html/head|div[@id='banner_parent']|button|ul|div[@id='feed_title']|span|div[@class='submit_event']|script"/>

但这正是问题所在:我现在正在拼凑一个模板 其匹配标准在源时可能容易出错 内容更改。

有没有更简单的指令可以完成同样的事情?我的目标是这样的:

<xsl:template match="node()[not(locations)]|script"/>

谢谢。

如果我理解正确,你只需要输出中的一些节点,其余的你不关心,在这个例子中我尝试只捕获 li 元素并丢弃其余的..不确定这是否是你想要的虽然想要 http://xsltransform.net/gWmuiKk

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<!-- Lets pretend li is interesting for you -->
<xsl:template match="li">
<xsl:text>Interesting Node Only!
</xsl:text>
</xsl:template>

<xsl:template match="@*|node()">
    <xsl:apply-templates select="@*|node()"/>
</xsl:template>
</xsl:transform>