Validating XML with Schema in Ruby

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.

4 Responses to “Validating XML with Schema in Ruby”

  1. Joe Says:

    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!

  2. AR Says:

    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]

  3. Stew Welbourne Says:

    I have only verified this particular code on Win32 (shame!!). I will verify it on my OSX host asap.

  4. Andy Watts Says:

    FYI, if rexml or libxml-ruby isn’t doing it for you, nokogiri is an new ruby-to-libxml library you may find useful.

Leave a Reply