Reputation: 2529
In my code I'm building an XML request. However, this simple fragment generates an error:
def create_gateways_request
@request_xml = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
xml.gateways(:ua => "#{@plugin_name} #{@version}") {
xml.merchant {
xml.account MSP['merchant']['account_id']
xml.site_id MSP['merchant']['site_id']
xml.site_secure_code MSP['merchant']['site_code']
}
xml.customer {
xml.country @customer[:country]
}
}
end
@request_xml.to_xml
end
The error:
RuntimeError: Document already has a root node
from /Users/scriptdude/.rvm/gems/ruby-1.9.2-p290/gems/nokogiri-1.5.2/lib/nokogiri/xml/document.rb:212:in `add_child'
from /Users/scriptdude/.rvm/gems/ruby-1.9.2-p290/gems/nokogiri-1.5.2/lib/nokogiri/xml/node.rb:549:in `parent='
from /Users/scriptdude/.rvm/gems/ruby-1.9.2-p290/gems/nokogiri-1.5.2/lib/nokogiri/xml/builder.rb:371:in `insert'
from /Users/scriptdude/.rvm/gems/ruby-1.9.2-p290/gems/nokogiri-1.5.2/lib/nokogiri/xml/builder.rb:363:in `method_missing'
from (irb):146
from /Users/scriptdude/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in `start'
from /Users/scriptdude/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in `start'
from /Users/scriptdude/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
The root node is <gateways>
, right?
What am I doing wrong here?
Upvotes: 1
Views: 4190
Reputation: 303391
I cannot reproduce this locally, but you might try this at the end of your method instead:
@request_xml.doc.to_xml
It appears that it thought that you were trying to add a new <to_xml>
node to the root of the document, and is complaining because you already have a <gateways>
element at the root. I cannot fathom why Nokogiri 1.5.2 would do this, however, as Builder does have a to_xml
method.
Here's my simple test that works for me:
require "nokogiri"
def do_it
@builder = Nokogiri::XML::Builder.new{ |x| x.root{ x.kid } }
@builder.to_xml
end
puts do_it
#=> <?xml version="1.0"?>
#=> <root>
#=> <kid/>
#=> </root>
p Nokogiri::VERSION
#=> "1.5.2"
Upvotes: 5