如何使用Nokogiri Builder创建带有命名空间根元素的XML文档 [英] How to create an XML document with a namespaced root element with Nokogiri Builder
问题描述
我正在为需要名称空间的XML数据实现导出器.我正在使用Nokogiri的XML Builder(版本1.4.0)来执行此操作,但是,我无法让Nokogiri创建带有名称空间的根节点.
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.
这有效:
Nokogiri::XML::Builder.new { |xml| xml.root('xmlns:foobar' => 'my-ns-url') }.to_xml
<?xml version="1.0"?>
<root xmlns:foobar="my-ns-url"/>
是这样的:
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>
但是,我需要类似<foo: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.
有人可以解决吗?
推荐答案
require 'rubygems'
require 'nokogiri'
puts Nokogiri::XML::Builder.new { |xml|
xml.root("xmlns:foo"=>"url") {
xml.parent.namespace = xml.parent.namespace_definitions.find{|ns|ns.prefix=="foo"}
xml['foo'].child
}
}.to_xml
在定义名称空间(即I.E.)之前,不能使用xml['foo']
.在将其作为参数传递给根节点之前,上面的代码事后将名称空间添加到了根节点.
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.
这篇关于如何使用Nokogiri Builder创建带有命名空间根元素的XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!