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=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
  require 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
 
  include System::Xml
  include System::Xml::Schema
  include System::IO
 
  def self.validate(xml, xsd_file)
    settings = XmlReaderSettings.new
    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(StringReader.new(xml), settings)
    while reader.read
    end
 
    return is_valid
  end
end

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

xml2
= "<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="http://www.w3.org/2001/XMLSchema">
   <xsd:element name="some">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="data" type="xsd:string"/>
         </xsd:sequence>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>

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 SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net 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.