如何使用 Nokogiri Builder 创建具有命名空间根元素的 XML 文档 [英] How to create an XML document with a namespaced root element with Nokogiri Builder

查看:21
本文介绍了如何使用 Nokogiri Builder 创建具有命名空间根元素的 XML 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为需要命名空间的 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.

我发现Define root node with a namespace?",但没有回复.

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 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

在定义命名空间之前,您不能使用 xml['foo'],即 I.E.在将其作为参数传递给根节点之前,因此,上面的代码在事后将命名空间添加到根节点.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆