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 =
  result = document.validate_schema(schema) do |message,flag|
    puts message

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.


6 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.

  5. Eric says:

    Thanks for the sample… I am trying to validate AIML xml schema, and I think your segment will do the basics of what I want. Amazing that this is so hard in Ruby world!

  6. michael says:

    I need a way to validate an XML with a XSD with Ruby and I ran across your blog. I’m working with Ruby 1.8.7 on WinXP. I’ve had nothing but problems trying to get libxml-ruby 1.1.4 or 1.1.3 to work. I am able to install the 1.1.3 msi version, but I get a rubygem version error when requiring the gem. Non-msi gems fail to install due to a zlib issue. Do you know of any other methods I could use to validate XML’s against XSD’s? I’ve spend 3 days scouring posts looking for a solution. Thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: