Class: XML_XSI

Inherits:
Object
  • Object
show all
Defined in:
lib/validate_xml_xsi.rb

Defined Under Namespace

Classes: Schema

Class Method Summary collapse

Class Method Details

.find_schema_locations(xml_doc) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/validate_xml_xsi.rb', line 27

def self.find_schema_locations(xml_doc)
  ## Include the default xml namespace
  schema_locations = {}

  ## Determine if the document has reference to the namespace "http://www.w3.org/2001/XMLSchema-instance"
  ## which is used for defining schemaLocations
  xsi_prefix = xml_doc.namespaces.invert['http://www.w3.org/2001/XMLSchema-instance']&.delete_prefix('xmlns:')

  ## Iterate over all the elements and find any xsi:schemaLocation attributes
  ## and build a hash of all of the namespaces and locations
  unless xsi_prefix.nil?
    xsi_loc = "#{xsi_prefix}:schemaLocation"
    xml_doc.search("//*[@#{xsi_loc}]").each do |elem|
      elem[xsi_loc].scan(/(\S+)\s+(\S+)/).each do |ns_set|
        if ns_loc = schema_locations[ns_set.first]
          unless ns_loc.eql?(ns_set.last)
            raise Schema::DocumentError.new("MISMATCHING namespace: #{ns_set.first} -> #{ns_loc} VS #{ns_set.last}")
          end
        else
          schema_locations[ns_set.first] = ns_set.last
        end
      end
    end
  end
  schema_locations
end

.parse(obj) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/validate_xml_xsi.rb', line 18

def self.parse(obj)
  filename = nil
  obj = File::read(filename = obj) if obj.is_a?(String) && File::exist?(obj)
  xml_doc = Nokogiri::XML.parse(obj) { |cfg| cfg.strict.pedantic.nonet }
  xml_doc.instance_variable_set('@filename', filename)
  xml_doc.define_singleton_method(:filename) { instance_variable_get('@filename') }
  xml_doc
end