Module: Lutaml::Xml::XsdValidator

Defined in:
lib/lutaml/xml/xsd_validator.rb

Overview

Validates a serialized XML string against an XSD schema file.

Backs the validate_xml_with class macro (issue #264). Nokogiri is required lazily so models that do not use XSD validation keep working on platforms/adapters without it (Opal, ox-only installs).

Compiled schemas are memoized by absolute path: the XSD files are constant for the life of the process, so each is read and compiled once and reused across every validate / validate_xml call.

Not to be confused with Schema::Xsd::SchemaValidator, which checks that an XSD document itself is well-formed XSD.

Class Method Summary collapse

Class Method Details

.validate(xml, schema_paths) ⇒ Array<Error::SchemaValidationError>

Returns one error per violation.

Parameters:

  • xml (String)

    an XML document

  • schema_paths (Array<String>)

    paths to XSD schema files

Returns:



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/lutaml/xml/xsd_validator.rb', line 28

def self.validate(xml, schema_paths)
  paths = Array(schema_paths)
  return [] if paths.empty?

  if RUBY_ENGINE == "opal"
    raise NotImplementedError,
          "XSD schema validation (validate_xml_with) requires the " \
          "nokogiri gem, which is not available under Opal."
  end

  ensure_nokogiri!
  # Strict parsing: libxml2 recovery would otherwise repair malformed
  # input and report it as schema-valid. NONET remains on by default.
  document = ::Nokogiri::XML(xml, &:strict)
  paths.flat_map do |path|
    schema_for(path)
      .validate(document)
      .map { |error| Error::SchemaValidationError.new(error.message, path) }
  end
end