Class: Nokogiri::XML::RelaxNG

Inherits:
NokogiriXmlSchema
  • Object
show all
Defined in:
lib/nokogiri/xml/relax_ng.rb,
lib/nokogiri/ffi/xml/relax_ng.rb,
ext/nokogiri/xml_relax_ng.c

Overview

Nokogiri::XML::RelaxNG is used for validating XML against a RelaxNG schema.

Synopsis

Validate an XML document against a RelaxNG schema. Loop over the errors that are returned and print them out:

schema  = Nokogiri::XML::RelaxNG(File.open(ADDRESS_SCHEMA_FILE))
doc     = Nokogiri::XML(File.open(ADDRESS_XML_FILE))

schema.validate(doc).each do |error|
  puts error.message
end

The list of errors are Nokogiri::XML::SyntaxError objects.

Class Method Summary collapse

Class Method Details

.from_document(doc) ⇒ Object

Create a new RelaxNG schema from the Nokogiri::XML::Document doc



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'ext/nokogiri/xml_relax_ng.c', line 99

def self.from_document document
  ctx = LibXML.xmlRelaxNGNewDocParserCtxt document.document.cstruct

  errors = []

  LibXML.xmlSetStructuredErrorFunc(nil, SyntaxError.error_array_pusher(errors))
  LibXML.xmlRelaxNGSetParserStructuredErrors(
    ctx, SyntaxError.error_array_pusher(errors), nil) unless Nokogiri.is_2_6_16?

  schema_ptr = LibXML.xmlRelaxNGParse(ctx)

  LibXML.xmlSetStructuredErrorFunc(nil, nil)
  LibXML.xmlRelaxNGFreeParserCtxt(ctx) unless Nokogiri.is_2_6_16?

  if schema_ptr.null?
    error = LibXML.xmlGetLastError
    if error
      raise SyntaxError.wrap(error)
    else
      raise RuntimeError, "Could not parse document"
    end
  end

  LibXML.xmlRelaxNGFreeParserCtxt(ctx) if Nokogiri.is_2_6_16?

  schema = allocate
  schema.cstruct = LibXML::XmlRelaxNG.new schema_ptr
  schema.errors = errors
  schema
end

.read_memory(string) ⇒ Object

Create a new RelaxNG from the contents of string



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'ext/nokogiri/xml_relax_ng.c', line 54

def self.read_memory content
  content_copy = FFI::MemoryPointer.from_string(content)
  ctx = LibXML.xmlRelaxNGNewMemParserCtxt(content_copy, content.length)

  errors = []

  LibXML.xmlSetStructuredErrorFunc(nil, SyntaxError.error_array_pusher(errors))
  LibXML.xmlRelaxNGSetParserStructuredErrors(
    ctx, SyntaxError.error_array_pusher(errors), nil) unless Nokogiri.is_2_6_16?

  schema_ptr = LibXML.xmlRelaxNGParse(ctx)

  LibXML.xmlSetStructuredErrorFunc(nil, nil)
  LibXML.xmlRelaxNGFreeParserCtxt(ctx)

  if schema_ptr.null?
    error = LibXML.xmlGetLastError
    if error
      raise SyntaxError.wrap(error)
    else
      raise RuntimeError, "Could not parse document"
    end
  end

  schema = allocate
  schema.cstruct = LibXML::XmlRelaxNG.new schema_ptr
  schema.errors = errors
  schema
end