I posted a long time back about my troubles in finding a way of performing schema validation in ruby (see Ruby and Xml Schema). At that time I was using REXML and only able to perform well-formedness checks based on basic structural integrity, but had no way to take an XSD and validate an instance document.
I’m pleased to say that there is a way to do this now, namely libxml-ruby. It’s available as a gem (gem install libxml-ruby) and the process is pretty simple:
document = LibXML::XML::Document.file(@xml_filename)
schema = LibXML::XML::Schema.new(@xsd_filename)
result = document.validate_schema(schema) do |message,flag|
log.debug(message)
puts message
end
I’ve found this to be a very neat piece of code for dealing with the kind of schema integrity checking I’m looking for, and as I blend this with a number of other java-based parses using the Ruby Java Bridge I get a pretty good, consistent perspective on validity.

October 31, 2008 at 11:45 pm |
Thanks for the code sample! I’ve been trying to learn xml schema as a replacement for dtds and this has been very helpful. Keep up the great work!
November 21, 2008 at 1:39 am |
Which platform and versions are you using.
I use the same code but I do run into following error
schema : #
res : true
/Users/xml_xsl.rb:32: [BUG] Bus Error
ruby 1.8.6 (2008-03-03) [universal-darwin9.0]
November 21, 2008 at 9:51 am |
I have only verified this particular code on Win32 (shame!!). I will verify it on my OSX host asap.
January 8, 2009 at 5:11 pm |
FYI, if rexml or libxml-ruby isn’t doing it for you, nokogiri is an new ruby-to-libxml library you may find useful.