如何使用Nokogiri删除除部分标签外的所有标签 [英] How to remove all tags except for some using Nokogiri

查看:23
本文介绍了如何使用Nokogiri删除除部分标签外的所有标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Nokogiri删除某个节点下除某些元素之外的所有标记? 例如,使用以下设置:

src = <<EOS
<html>
  <body>
    <p>
      Hello <i>world</i>!
      This is <em>another</em> line.
      <p><h3>And a paragraph <em>with</em> a heading.</h3></p>
      <b>Third line.</b>
    </p>
  </body>
</html>
EOS

doc = Nokogiri::HTML(src)    
para = doc.at('//p')
如何删除段落中除<;i>;和<;b&>元素之外的所有元素(同时保留其内容)? 因此,结果将是:

<html>
  <body>
    <p>
      Hello <i>world</i>!
      This is another line.
      And a paragraph with a heading.
      <b>Third line.</b>
    </p>
  </body>
</html>

推荐答案

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>

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

    <xsl:template match="em | p/p | h3">
        <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>

应用于您的样本,结果将为:

<html>
    <body>
        <p>
      Hello 
            <i>world</i>!
      This is another line.
      And a paragraph with a heading.
            <b>Third line.</b>
        </p>
    </body>
</html>

根据批注中的请求进行编辑。

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>

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

    <xsl:template match="p//*[not(self::i or self::b)]">
        <xsl:apply-templates/>
    </xsl:template>
</xsl:stylesheet>

这将删除p中的所有元素(标记,而不是字符串值),ib元素除外。

这篇关于如何使用Nokogiri删除除部分标签外的所有标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆