Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

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

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 a root node with a namespace.

This works:

Nokogiri::XML::Builder.new { |xml| xml.root('xmlns:foobar' => 'my-ns-url') }.to_xml

<?xml version="1.0"?>
<root xmlns:foobar="my-ns-url"/>

As does this:

Nokogiri::XML::Builder.new do |xml| 
  xml.root('xmlns:foobar' => 'my-ns-url') { xml['foobar'].child }
end.to_xml

<?xml version="1.0"?>
<root xmlns:foobar="my-ns-url">
  <foobar:child/>
</root>

However, I need something like <foo:root> and this doesn't work:

Nokogiri::XML::Builder.new { |xml| xml['foobar'].root('xmlns:foobar' => 'my-ns-url') }.to_xml

NoMethodError: undefined method `namespace_definitions' for #<Nokogiri::XML::Document:0x11bfef8 name="document">

Namespaces have to be defined before use, apparently, so there's no way to add one to the root node.

I found "Define root node with a namespace?" on the Nokogiri mailing list, but it had no replies.

Does anyone have a solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...