Created
February 25, 2011 03:56
-
-
Save mxriverlynn/843340 to your computer and use it in GitHub Desktop.
validate an xml document against an xml schema in ironruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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