genkilabs
genkilabs

Reputation: 2986

How to add XML string to Nokogiri Builder

I have an existing Nokogiri builder and some xml nodes in a string from a different source. How can I add this string to my builder?

str = "<options><cc>true</cc></options>"
xml = Nokogiri::XML::Builder.new do |q|
  q.query do |f|
    f.name "awesome"
    f.filter str
  end
end

This escapes str into something like:

xml.to_xml
=> "<?xml version=\"1.0\"?>\n<query>\n  <name>awesome</name>\n  <filter>&lt;options&gt;&lt;cc&gt;true&lt;/cc&gt;&lt;/options&gt;</filter>\n</query>\n"

I have found many, many similar things, including nesting builders and using the << operator, but nothing works to insert a full xml node tree into a builder block. How can I make that string into real nodes?

Upvotes: 6

Views: 2384

Answers (2)

genkilabs
genkilabs

Reputation: 2986

And, as usual, I found the answer shortly after posting...

xml = Nokogiri::XML::Builder.new do |q|
  q.query do |f|
    f.name "awesome"
    f.__send__ :insert, Nokogiri::XML::DocumentFragment.parse( str )
  end
end.to_xml

Gives you

=> "<?xml version=\"1.0\"?>\n<query>\n  <name>awesome</name>\n  <options>\n    <cc>true</cc>\n  </options>\n</query>\n"

EDIT: This way worked for me when << failed for some unknown reason. However, as others have pointed out it works by directly accessing the :insert method which was intended to be protected. Consider it both "bad practice" and a last resort.

Upvotes: 0

matt
matt

Reputation: 79723

What problems did you find using <<? This works for me:

xml = Nokogiri::XML::Builder.new do |q|
  q.query do |f|
    f.name "awesome"
    f << str
  end
end

and avoids using the private insert method.

Upvotes: 12

Related Questions