2012-03-11 20 views
4

これは私がしたいことです: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> 

答えて

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> 
+1

感謝を印刷し、どの本を試してみてください、これは非常に便利です。私はあなたのポストからトンを学んでいます。私はDATA定数や!〜演算子については考えていませんでしたが、私はまだxpathをすべて理解しているとは確信していませんが –

関連する問題