Generate Ruby Classes from XSD

2019-03-11 13:04发布

Is there a way to generate Ruby classes (maybe even ActiveResource classes) from an XSD so that they contain a way to serialize the classes to xml valid for the initial XSD?

I know that soap4r has xsd2ruby but it appears that the generated ruby classes cannot be easily serialized to xml.

3条回答
Deceive 欺骗
2楼-- · 2019-03-11 13:12

Mark,

Though this was asked a while ago, I came across a solution and thought it might help folks in the future.

My need was similar. I have a .xsd from a colleague and would like to generate a class file from it. My hope is that I'll be able to easily marshall the object and pass it to his RESTful end-point, where his Java server will unmarshall the payload and dynamically build the object on his side with no additional effort.

The solution I found was to get the soap4r from https://github.com/rubyjedi/soap4r. I made the two *.rb files in the bin directory executable and then ran:

bin/xsd2ruby.rb --xsd <source>.xsd --classdef <filename_prefix>

This generated a new file with each of the xsd:complexType implemented as a class. All other complex type were also generated with the correct inheritance relationships and all xsd:element was defined as an instance variable and a class initializer also defined.

Running xsd2ruby.rb by itself yielded the options:

~/src/test/soap4r:bin/xsd2ruby.rb 
Usage: bin/xsd2ruby.rb --xsd xsd_location [options]
  xsd_location: filename or URL

Example:
  bin/xsd2ruby.rb --xsd myapp.xsd --classdef foo

Options:
  --xsd xsd_location
  --classdef [filenameprefix]
  --mapping_registry
  --mapper
  --module_path [Module::Path::Name]
  --force
  --quiet

For the sake of completeness, I extended my class with the following (this is a "Prospect" class):

class Prospect
  include Enumerable
  def each(&block)
    self.instance_variables.collect{|v| (v.gsub /@/, '').to_sym }.each(&block)
  end
end

This let me use it as the body of an Net::HTTP::Post request.

To the question of a free to_xml: I haven't found it. The ruby Object comes with a to_yaml and to_json out of the box, but I've not found any simple conversion to XML. So it came down to a roll my own "to_xml".

Hope this helps.

查看更多
smile是对你的礼貌
3楼-- · 2019-03-11 13:31

It appears that this might work.

require 'xsd/mapping' XSD::Mapping.obj2xml(xsdBasedObject)

查看更多
爷、活的狠高调
4楼-- · 2019-03-11 13:32

Shameless self promotion (hope this is okay on stackoverflow) but I'm working on an open source project to do just that

Its still a work in progress (feel free to send patches) but the ultimate goal is to convert XSD to/from Ruby classes (which it does now) and convert XML conforming to that XSD to/from instances of those classes.

查看更多
登录 后发表回答