views:

58

answers:

1

Say, we have an HTML, in which, all ...

<div class="replace-me">
</div>

... must be replaced with

<video src='my_video.mov'></video>

The code is following:

doc.css("div.replace-me").each do |div|
  div.replace "<video src='my_video.mov'></video>"
end

It's simple, but, unfortunately, it does't work for me. Nokogiri crashes with follwing error:

undefined method children' for nil:NilClass /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/whiny_nil.rb:52:inmethod_missing' /Library/Ruby/Gems/1.8/gems/nokogiri-1.4.2/lib/nokogiri/html/document_fragment.rb:16:in initialize' /Library/Ruby/Gems/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node.rb:424:innew' /Library/Ruby/Gems/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node.rb:424:in fragment' /Library/Ruby/Gems/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node.rb:776:incoerce' /Library/Ruby/Gems/1.8/gems/nokogiri-1.4.2/lib/nokogiri/xml/node.rb:331:in `replace'

Replacing with primitive div does works:

doc.css("div.replace-me").each do |div|
  div.replace "<div>Test</div>"
end

Is this a Nokogiri bug, or i do something wrong ?

PS: the same issue with "add_child", "inner_html" and other setters for this purpose

A: 

I will quote my comment from your previous question:

This happens because of HTML strictness (HTML has a predefined set of elements). Replace Nokogiri::HTML( self.content ) with Nokogiri::XML( self.content ) and do not forget to add a DOCTYPE declaration manually later.

floatless
OK. Let's move to this post :)It seems to work with replacement. But another problem - when i try to save the modified document's part back to self.content, i get only those parts, that have replaced the old ones. But another elements, that were somewhere around, and were not modified (in self.content) - are gone...
AntonAL
Very strange. I'm trying to understand why. Could you show your source HTML before any replacements?
floatless