Validating Xml Against XSD Schema In IronRuby

There’s a thousand examples of how to validate an xml document against an xsd schema in C# around the web, but I had a hard time finding one that worked in IronRuby. So I translated some of the C# examples I found into a working IronRuby version.

class XmlValidator
  require 'System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'
  require 'System.Xml, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'
  include System::Xml
  include System::Xml::Schema
  include System::IO
  def self.validate(xml, xsd_file)
    settings =
    settings.validation_type = ValidationType.Schema;
    settings.schemas.add(nil, xsd_file)
    is_valid = true
    settings.validation_event_handler { |s, e|
      is_valid = false if e.severity == XmlSeverityType.error
    reader = XmlReader.create(, settings)
    return is_valid

This code runs against IronRuby 1.0 or higher, and runs against the .NET 2.0 versions of System and System.Xml assemblies. Here’s the example that I wrote to ensure this works:

xsd_file = "schema.xsd"
xml = "<some><data>goes here</data></some>"
puts XmlValidator.validate(xml, xsd_file) # => true

= "<something><that>should fail</that></something>"
puts XmlValidator.validate(xml2, xsd_file) # => false

And here’s the schema file used to validate the xml:

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="">
   <xsd:element name="some">
            <xsd:element name="data" type="xsd:string"/>

For a syntax-highlited version of all this, see this Gist.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs - the amazingly awesome podcast audio hosting service that everyone should be using, and where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in .NET, IronRuby, Ruby. Bookmark the permalink. Follow any comments here with the RSS feed for this post.