I’m using Nokogiri to build some XML. I need to create a node in a namespace that declares that same namespace. As usual with XML, this process is proving to be annoyingly difficult. I need XML that looks like
<?xml version="1.0"?>
<bar:foo xmlns:bar="http://www.bar.com">
<bar:baz>baz</bar:baz>
</bar:foo>
This (obviously) doesn’t give it to me:
builder=Nokogiri::XML::Builder.new do |xml|
# Doesn't put foo in the bar namespace
xml.foo( "xmlns:bar" => "http://www.bar.com") do
xml['bar'].baz "baz"
end
end
Neither does this:
builder=Nokogiri::XML::Builder.new do |xml|
# undefined method `namespace_definitions' for #<Nokogiri::XML::Document:0x3fcc11b590ec name="document">
xml['bar'].foo( "xmlns:bar" => "http://www.bar.com") do
xml['bar'].baz "baz"
end
end
How do I get Nokogiri to give me the XML I want?
Oh, here we go: Adding namespace using Nokogiri's XML Builder
Apparently you either can’t do this during creation, or it’s so difficult that even SO can’t figure it out. But you can do it after creation:
That was annoying, though.