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

</div>

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

</pre>

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"

</div>

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

</pre>

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

<?xml version="1.0"?>

</div>

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

</pre>

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

How To Have Bundler Load A Gem From The Vendor Folder Into A Rails 3 App