使用命名空间节点从ruby类生成xml

时间:2013-03-26 12:40:33

标签: ruby xml object mapping

我有一个像这样的红宝石课:

class MyResponse
    attr_accessor :results
    def initialize(results = nil)
        @results = results
    end
end

使用此代码,

resp = MyResponse.new 'Response text'
qname = XSD::QName.new('http://www.w3schools.com/furniture', :MyResponse)
xml = XSD::Mapping.obj2xml(resp, qname)
puts xml

我设法从该类生成这个xml:

<?xml version="1.0" encoding="utf-8" ?>
<n1:MyResponse xmlns:n1="http://www.w3schools.com/furniture">
  <results>Response text</results>
</n1:MyResponse>

但我希望<results>节点也有<n1:results>

这样的名称空间前缀

我正在努力解决这个问题很长一段时间。请帮帮我。

编辑:我只需要所有节点都有名称空间前缀。我对任何其他方式或图书馆开放。

2 个答案:

答案 0 :(得分:2)

我喜欢用ROXML读写XML。遗憾的是,文档并不完整,但可以直接从code documentation检索许多信息。我没有成功地给出一个完全符合你要求的例子(xmlns节点只有xmlns而不是xmlns:n1)但是你可以完成它:

require 'roxml'

class Response
    include ROXML

    xml_name 'MyResponse'

    xml_namespace :n1

    xml_accessor :xmlns, from: :attr
    xml_accessor :results, from: "n1:results"

    def initialize
        @xmlns = "http://www.w3schools.com/furniture"
    end

end

response = Response.new
response.results = "Response text"
puts '<?xml version="1.0" encoding="utf-8" ?>'
puts response.to_xml
# <?xml version="1.0" encoding="utf-8" ?>
# <n1:MyResponse xmlns="http://www.w3schools.com/furniture">
#   <n1:results>Response text</n1:results>
# </n1:MyResponse>

答案 1 :(得分:1)

从语义上讲,您不需要为每个节点添加名称空间前缀,以使它们成为同一名称空间的所有成员。

出于各种目的,此XML可以满足您的需求:

<?xml version="1.0" encoding="utf-8" ?>
<MyResponse xmlns="http://www.w3schools.com/furniture">
  <results>Response text</results>
</MyResponse>

考虑到这一点,您可以使用BuilderResponse XML包装到其中(假设它实现了to_xml方法 - 所有ActiveModel类都这样做):< / p>

b = ::Builder::XmlMarkup.new
xml = b.MyResponse :xmlns => 'http://www.w3schools.com/furniture' do
  b << resp.to_xml
end