Reputation: 3275
I have a ruby class like this:
class MyResponse
attr_accessor :results
def initialize(results = nil)
@results = results
end
end
With this code,
resp = MyResponse.new 'Response text'
qname = XSD::QName.new('http://www.w3schools.com/furniture', :MyResponse)
xml = XSD::Mapping.obj2xml(resp, qname)
puts xml
I managed to generate this xml from that class:
<?xml version="1.0" encoding="utf-8" ?>
<n1:MyResponse xmlns:n1="http://www.w3schools.com/furniture">
<results>Response text</results>
</n1:MyResponse>
But I would like the <results>
node also to have the namespace prefix like <n1:results>
I am trying figure this out for a long time. Please help me out.
Edit: I just need all the nodes to have namespace prefix. I'm open to any other way or libraries.
Upvotes: 2
Views: 254
Reputation: 25280
Semantically speaking, you don't need to prefix every node with the namespace prefix, in order to make them all member of the same namespace.
This XML is, for all purposes, equivalent for your needs:
<?xml version="1.0" encoding="utf-8" ?>
<MyResponse xmlns="http://www.w3schools.com/furniture">
<results>Response text</results>
</MyResponse>
With that in mind, you can use Builder
to wrap the Response
XML into that (assuming it implements the to_xml
method – all ActiveModel
classes do):
b = ::Builder::XmlMarkup.new
xml = b.MyResponse :xmlns => 'http://www.w3schools.com/furniture' do
b << resp.to_xml
end
Upvotes: 1
Reputation: 796
I love to read and write XML with ROXML. Unfortunately the documentation is not complete, although can retrieve many informations directly from the code documentation. I did not succeed in giving an example that exactly meet your requirements (the xmlns node is only xmlns not xmlns:n1) but maybe you can complete it:
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>
Upvotes: 2