How to create an XML document with a namespaced root element with Nokogiri Builder

后端 未结 3 764
执笔经年
执笔经年 2020-12-15 09:02

I\'m implementing an exporter for XML data that requires namespaces. I\'m using Nokogiri\'s XML Builder (version 1.4.0) to do this, however, I can\'t get Nokogiri to create

3条回答
  •  暖寄归人
    2020-12-15 09:13

    require 'rubygems'
    require 'nokogiri'
    
    puts Nokogiri::XML::Builder.new do |xml| 
      xml.root("xmlns:foo"=>"url") do
        xml.parent.namespace = xml.parent.namespace_definitions.find{|ns|ns.prefix=="foo"}
        xml['foo'].child
      end
    end.to_xml
    

    You cannot use xml['foo'] before the namespace is defined, I.E. before you pass it as an argument to the root node, thus, the code above added the namespace after-the-fact to the root node.

提交回复
热议问题