When using Nokogiri to validate an XML document against multiple XML Schema files using import declarations, ensure that you use File.open
rather than File.read
as shown in the Nokogiri::XML::Schema documentation. This will allow Nokogiri to navigate to and read these imported schemas.
Thanks to this StackOverflow post.
a.xsd
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:b="ns_b" targetNamespace="ns_a"> <xs:import namespace="ns_b" schemaLocation="b.xsd"/> <xs:element name="Foo" type="b:BarType" /> </xs:schema>
b.xsd
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="ns_b"> <xs:complexType name="BarType"> <xs:simpleContent> <xs:extension base="xs:string" /> </xs:simpleContent> </xs:complexType> </xs:schema>
example.xml
<?xml version="1.0"?> <Foo xmlns="ns_a">Hello World</Foo>
validate.rb
xsd = Nokogiri::XML::Schema(File.open('a.xsd')) doc = Nokogiri::XML(File.read('example.xml')) xsd.validate(doc).each do |error| puts error.message end
Leave a Reply