Using Nokogiri HTML Builder to create fragment with multiple root nodes
Asked Answered
K

2

16

Well I have a simple problem with Nokogiri. I want to make Nokogiri::HTML::Builder to make an HTML fragment of the following form:

<div>
#Some stuff in here
</div>
<div>
#Some other stuff in here
</div>

When trying to do:

@builder = Nokogiri::HTML::Builder.new(:encoding => 'UTF-8') do |doc|
    doc.div {
      doc.p "first test"
    }
    doc.div {
      doc.p "second test"
    }
  end
@builder.to_html

I get an error: Document has already a root node, which I partly understand. I know I am not wrapping the whole thing into tags (which Nokogiri expects as Nokogiri::HTML::Builder inherits from Nokogiri::XML::Builder and an XML document must have a root node). But I am not building an XML document.

Am I missing something? Any kind of help is much appreciated.

Kagera answered 5/2, 2011 at 11:51 Comment(0)
Y
27

As you noted, Builder will not allow you to build an HTML document with multiple root nodes. You'll need to use DocumentFragment

@doc = Nokogiri::HTML::DocumentFragment.parse ""

Nokogiri::HTML::Builder.with(@doc) do |doc|
    doc.div {
      doc.p "first test"
    }
    doc.div {
      doc.p "second test"
    }
end

puts @doc.to_html
Yacano answered 5/2, 2011 at 14:45 Comment(1)
+1 I didn't know that Builder could accept an arbitrary document. Nice work.Horme
H
0

Here is what I did for replacing images src attributes:

  doc = Nokogiri::HTML(html)
   doc.xpath("//img").each do |img|
     img.attributes["src"].value = Absolute_asset_path(img.attributes["src"].value)
  end
  doc.to_html     
Humfried answered 18/10, 2017 at 19:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.