【问题标题】:Mapping XML to Ruby objects将 XML 映射到 Ruby 对象
【发布时间】:2013-01-21 11:37:52
【问题描述】:

我想在 ruby​​ 和其他 XML 应用程序之间进行通信。我已经为这种通信定义了一个模式,并且我正在寻找将 Ruby 中的数据转换为 XML 的最佳方法,反之亦然。

我有一个 XML 文档 my_document.xml:

<myDocument>
  <number>1</number>
  <distance units="km">20</distance>
</myDocument>

符合 Schema 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。
  • 我没有——老实说,构建类似于我正在寻找的东西的复杂性源于 XML 和 XSD 的复杂性;我最终构建了特定的映射类(并最终转向使用 JSON)

标签: ruby xml xsd


【解决方案1】:

你试过Nokogiri吗? Slop decorator 将method_missing 实现到文档中的方式基本上复制了您正在寻找的功能。

【讨论】:

  • 看起来棒极了!干杯:)
猜你喜欢
  • 2021-04-13
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 2010-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多