1

在我的代码中,我正在构建一个 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>,对吧?

我在这里做错了什么?

4

1 回答 1

3

我无法在本地重现此内容,但您可以在方法结束时尝试此操作:

@request_xml.doc.to_xml

它似乎认为您正在尝试向<to_xml>文档的根目录添加一个新节点,并且正在抱怨,因为您已经<gateways>在根目录中有一个元素。但是,我无法理解为什么 Nokogiri 1.5.2 会这样做,因为Builder 确实有一个to_xml方法

这是对我有用的简单测试:

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"
于 2012-04-17T16:10:39.677 回答