我想在Ruby中與ruby和其他應用程序進行通信。我爲這個通信定義了一個模式,我正在尋找從Ruby中的數據到XML的轉換的最佳方式,反之亦然。將XML映射到Ruby對象
我有一個XML文檔my_document.xml
:
<myDocument>
<number>1</number>
<distance units="km">20</distance>
</myDocument>
這符合一個模式my_document_type.xsd
(我將不願意打擾這裏寫出來)。
現在我想像從XSD自動生成以下類 - 是否合理或可行?
# Represents a document created in the form of my_document_type.xsd
class MyDocument
attr_accessor :number, :distance, :distance_units
# Allows me to create this object from data in Ruby
def initialize(data)
@number = data['number']
@distance = data['distance']
@distance_units = data['distance_units']
end
# Takes an XML document of the correct form my_document.xml and populates internal systems
def self.from_xml(xml)
# Reads the XML and populates:
doc = ALibrary.load(xml)
@number = doc.xpath('/number').text()
@distance = doc.xpath('/distance').text()
@distance_units = doc.xpath('/distance').attr('units') # Or whatever
end
def to_xml
# Jiggery pokery
end
end
所以,現在我可以這樣做:
require 'awesomelibrary'
awesome_class = AwesomeLibrary.load_from_xsd('my_document_type.xsd')
doc = awesome_class.from_xml('my_document.xml')
p doc.distance # => 20
p doc.distance_units # => 'km'
而且我還可以做
doc = awesome_class.new('number' => 10, 'distance_units' => 'inches', 'distance' => '5')
p doc.to_xml
並獲得:
<myDocument>
<number>10</number>
<distance units="inches">5</distance>
</myDocument>
這聽起來相當激烈功能我,所以我不期待一個完整的答案,但是任何有關庫已經這樣做的提示(我嘗試過使用RXSD,但我不知道如何讓它做到這一點)或任何可行性的想法等等。
在此先感謝!
你有沒有最終找到這個問題的解決方案? Nokogiri :: Slop似乎提供了一些您請求的對象訪問權限,但它無助於對象創建方面。我在構建模型(來自xsd)時有類似的用例,可以驗證它,並將其序列化爲xml。 – RLB
我沒有 - 老實說,構建類似我所期望的複雜性源於XML和XSD的複雜性;我最終建立了特定的映射類(並最終轉向使用JSON) –