Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created February 25, 2011 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxriverlynn/843340 to your computer and use it in GitHub Desktop.
Save mxriverlynn/843340 to your computer and use it in GitHub Desktop.
validate an xml document against an xml schema in ironruby
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
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
<?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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment