Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Last active December 14, 2015 08:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshmcarthur/5059859 to your computer and use it in GitHub Desktop.
Save joshmcarthur/5059859 to your computer and use it in GitHub Desktop.
Quick demo of validating an XML document against a schema
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