Last active
December 14, 2015 08:48
-
-
Save joshmcarthur/5059859 to your computer and use it in GitHub Desktop.
Quick demo of validating an XML document against a schema
This file contains hidden or 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
require 'nokogiri' | |
# Public: Find the absolute path to a file | |
# | |
# This method finds a file that is relative to the | |
# location of the script, expanding anything that | |
# needs expanding (~, etc.) | |
# | |
# filename - the filename to find | |
# Returns the absolute path to the file | |
def absolute_path(filename) | |
File.expand_path( | |
File.join( | |
File.dirname(__FILE__), | |
filename | |
) | |
) | |
end | |
schema = Nokogiri::XML::Schema(File.read(absolute_path('schema.xsd'))) | |
document = Nokogiri::XML::Document(File.read(absolute_path('document.xml'))) | |
errors = schema.validate(document).map { |error| error.message } | |
unless errors.empty? | |
puts "Document did not validate: #{errors.join(', ')}" | |
else | |
puts "Document validated!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment