2012-04-17 79 views
1

在我的代码中,我构建了一个XML请求。然而,这个简单的片段产生一个错误:Nokogiri XML Builder错误 - >“文档已经有一个根节点”

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

我有正确的XML结构发送到web服务,所以我不能拿出。 – 2012-04-17 14:13:49

+0

也许值得在样本XML文档中添加它如何格式化。 – Jonathan 2012-04-17 14:31:59

+0

与defaye同意。需要一个XML匹配的例子,也是一个我们可以重现它的简单方法。请取出您用于构建此XML的所有变量并向我们显示。 – 2012-04-17 14:44:05

回答

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" 
相关问题