Checking the circuit with Nokogiri

I am trying to validate an XML document against a dozen or so schemas using Nokogiri. Currently, I have a root schema file that imports all other schemas, and I confirm this.

Can I point to each schema file from the XML file itself and look for Nokogiri in the XML file to validate the schemas?

+6
source share
1 answer

The correct way to refer to several schemas for which there is a schemaLocation attribute to validate the XML file:

 <?xml version="1.0"?> <foo xmlns="http://bar.com/foo" xmlns:bz="http://biz.biz/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://bar.com/foo http://www.bar.com/schemas/foo.xsd http://biz.biz/ http://biz.biz/xml/ns/bz.xsd"> 

For each namespace in your document, you specify a pair of space-delimited values: the namespace URI, followed by a β€œhint” about where to find the schema for that namespace. If you provide a complete URI for each hint, you can handle this with Nokogiri as such:

 require 'nokogiri' require 'open-uri' doc = Nokogiri.XML( my_xml ) schemata_by_ns = Hash[ doc.root['schemaLocation'].scan(/(\S+)\s+(\S+)/) ] schemata_by_ns.each do |ns,xsd_uri| xsd = Nokogiri::XML.Schema(open(xsd_uri)) xsd.validate(doc).each do |error| puts error.message end end 

Disclaimer: I have never tried to validate a single XML document using multiple schemas with names with Nokogiri before. Thus, I have no direct experience to ensure that the above verification will work. The verification code is based only on the Nokogiri schema verification documentation .

+7
source

Source: https://habr.com/ru/post/908344/


All Articles