如何复制<p>元素中的所有内容,而忽略<span>标签,但不复制其内容

时间:2019-04-12 13:51:54

标签: xslt xslt-1.0

我有一些看起来像这样的HTML:

<div>
  <p><span class="selected-for-presentation">This is a <u><em><strong>very cool</strong></em></u> sentence...</span></p>
  <p>This is a <u><em><strong><span class="selected-for-presentation">very</span> cool</strong></em></u> sentence...</p>
</div>

并且我正在尝试编写一些XSLT,它复制了段落的全部内容,而省略了<span>标签,但没有内容。因此结果应如下所示:

<div>
  <p>This is a <u><em><strong>very cool</strong></em></u> sentence...</p>
  <p>This is a <u><em><strong>very cool</strong></em></u> sentence...</p>
</div>

到目前为止,这是我的XSLT,它适用于第一段,但不适用于第二段:

<xsl:template match="p">
  <p>
    <xsl:apply-templates mode="copy_span_content"/>
  </p>
</xsl:template>

<xsl:template match="strong" mode="copy_span_content">
  <xsl:apply-templates mode="copy_span_content"/>
</xsl:template>

<xsl:template match="em" mode="copy_span_content">
  <xsl:apply-templates mode="copy_span_content"/>
</xsl:template>

<xsl:template match="u" mode="copy_span_content">
  <xsl:apply-templates mode="copy_span_content"/>
</xsl:template>

<xsl:template match="span" mode="copy_span_content">
  <xsl:copy-of select="./node()"/>
</xsl:template>

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果您只想删除span并保留其他所有内容,则有一种简单得多的方法,那就是使用Identity Template处理所有内容的复制,并使用一个覆盖模板来跳过span,但继续处理其子项。

尝试一下

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:output method="xml" />

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

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

答案 1 :(得分:0)

由于Tim C(see below)的建议,我提出了一个完美的解决方案。我无法像建议中那样简单,因为我正在使用的HTML文件比我提供的摘录更加复杂,并且我的XSLT文件已导入到更大的文件中,并且我不希望身份模板应用于其他元素。

我想出的解决方案:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="p[descendant::span]">
        <xsl:apply-templates select="." mode="copy_without_span_tags"/>
        <!-- There is more stuff that goes in here in my actual template.-->
    </xsl:template>

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

    <xsl:template match="span" mode="copy_without_span_tags">
        <xsl:apply-templates/>
    </xsl:template>

</xsl:stylesheet>