从Nokogiri的元素中删除外部标签?

时间:2012-03-11 02:49:19

标签: xml parsing 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>

1 个答案:

答案 0 :(得分:8)

试试这个

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 !~ /\A\s*\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>