使用Nokogiri删除元素的外部标记



这就是我想要做的:

删除类为"none"的"span"节点。

删除"多余"节点,但将文本保留在其中。

删除任何"br"节点,并将其替换为"p"节点

<p class="normal">
    <span class="none">
        <extra>Some text goes here</extra>
    </span>
    <span class="none">
        <br/>
    </span>
    <span class="none">
        <extra>Some other text goes here</extra>
        <br/>
    </span>
</p>

这就是我想要实现的输出:

<p class="normal">Some text goes here</p>
<p class="normal">Some other text goes here</p>

到目前为止,我已经尝试过了:

doc.xpath('html/body/p/span').each do |span|
    span.attribute_nodes.each do |a|
       if a.value == "none"
          span.children.each do |child|
             span.parent << child
          end
          span.remove
       end
    end
end

但这是我得到的输出,它甚至没有按照正确的顺序:

<p class="normal"><br /><br />Some text goes hereSome other text goes here</p>

试试这个

require 'rubygems'
require 'nokogiri'
doc = Nokogiri::XML(DATA)
doc.css("span.none, extra").each do |span|
  span.swap(span.children)
end
# via http://stackoverflow.com/questions/8937846/how-do-i-wrap-html-untagged-text-with-p-tag-using-nokogiri
doc.search("//br/preceding-sibling::text()|//br/following-sibling::text()").each do |node|
  if node.content !~ /As*Z/
    node.replace(doc.create_element('p', node))
  end
end
doc.css('br').remove
puts doc
__END__
<p class="normal">
    <span class="none">
        <extra>Some text goes here</extra>
    </span>
    <span class="none">
        <br/>
    </span>
    <span class="none">
        <extra>Some other text goes here</extra>
        <br/>
    </span>
</p>

哪个打印

<?xml version="1.0"?>
<p class="normal">
        <p>Some text goes here</p>


        <p>Some other text goes here</p>

</p>

相关内容

  • 没有找到相关文章