use warnings;
use strict;
use utf8;
use XML::LibXML;
use URI;
use HTTP::Tiny;
my $http = HTTP::Tiny->new;
my %cache;
XML::LibXML::externalEntityLoader(sub {
my ($url, $id) = @_;
die "Can't handle ID '$id'" if length $id;
my $uri = URI->new($url);
my $file;
if (!$uri->scheme) { $file = $url }
elsif ($uri->scheme eq 'file') { $file = $uri->path }
if (defined $file) {
warn "'$uri' => Loading '$file' from disk\n"; #Debug
open my $fh, '<', $file or die "$file: $!";
my $data = do { local $/; <$fh> };
close $fh;
return $data;
} # else
die "Can't handle URL scheme: ".$uri->scheme
unless $uri->scheme=~/\Ahttps?\z/i;
if (!defined $cache{$uri}) {
warn "'$uri' => Fetching...\n"; #Debug
my $resp = $http->get($uri);
die "$uri: $resp->{status} $resp->{reason}\n"
unless $resp->{success};
$cache{$uri} = $resp->{content};
}
else { warn "'$uri' => Cached\n"; } #Debug
return $cache{$uri};
});
print "Loading schema...\n";
my $xsd = XML::LibXML::Schema->new( location => 'schema.xsd' );
my @xmls = (<<'END_XML_ONE',<<'END_XML_TWO',<<'END_XML_THREE');
x
END_XML_ONE
x
END_XML_TWO
x
END_XML_THREE
my $i = 1;
for my $xml (@xmls) {
print "Validating XML #$i...\n";
my $doc = XML::LibXML->load_xml( string => $xml );
if ( eval { $xsd->validate($doc); 1 } )
{ print "=> Valid!\n" }
else { print "=> Invalid! $@" }
} continue { $i++ }