在我的代码中,我正在构建XML请求。但是,这个简单的片段会产生错误:
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
错误:
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>'
根节点是<gateways>
,对吧?
我在这里做错了什么?
答案 0 :(得分:3)
我无法在本地重现此内容,但您可以在方法结束时尝试此操作:
@request_xml.doc.to_xml
它似乎认为您正在尝试将新的<to_xml>
节点添加到文档的根目录,并且正在抱怨,因为您已在根目录中拥有<gateways>
元素。我无法理解为什么Nokogiri 1.5.2会这样做,Builder does have a to_xml
method。
这是我的简单测试,对我有用:
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"