2013-03-26 52 views
2

我有一個Ruby類是這樣的:生成Ruby類XML與命名空間節點

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>節點也有像這樣的名稱空間前綴

我想弄清楚很長一段時間。請幫助我。

編輯:我只需要所有節點都有名稱空間前綴。我對任何其他方式或圖書館都是開放的。

回答

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

從語義上來說,你不需要每次前綴節點與命名空間前綴,以使它們成爲同一個命名空間的所有成員。

此XML,出於各種目的,相當於爲您的需求:

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

考慮到這一點,你可以用Builder包裹Response XML成(假設它實現了to_xml方法 - 所有ActiveModel類):

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