Validate an XML document against an XSD schema with Ruby and Nokogiri

Posted Over 13 years ago. Visible to the public.

The code below shows a method #validate which uses Nokogiri to validate an XML document against an XSD schema. It returns an array of Nokogiri::XML::SyntaxError Show archive.org snapshot objects.

require 'rubygems'
gem 'nokogiri'
require 'nokogiri'

def validate(document_path, schema_path, root_element)
  schema = Nokogiri::XML::Schema(File.read(schema_path))
  document = Nokogiri::XML(File.read(document_path))
  schema.validate(document.xpath("//#{root_element}").to_s)
end

validate('input.xml', 'schema.xdf', 'container').each do |error|
  puts error.message
end

This note was contributed by Matthias Marschall from the Agile Web Development & Operations Show archive.org snapshot blog.

Henning Koch
Last edit
About 13 years ago
Keywords
validation, validations
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-02-17 13:03)