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 XmlValidatorrequire 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'require 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
include System::Xmlinclude System::Xml::Schemainclude System::IO
def self.validate(xml, xsd_file)settings = XmlReaderSettings.newsettings.validation_type = ValidationType.Schema;settings.schemas.add(nil, xsd_file)
is_valid = truesettings.validation_event_handler { |s, e|is_valid = false if e.severity == XmlSeverityType.error}
reader = XmlReader.create(StringReader.new(xml), settings)while reader.readend
return is_validendend
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.
Post Footer automatically generated by Add Post Footer Plugin for wordpress.
