Validating XML in Perl with libxml and an XSD file

2019-07-01 13:39发布

问题:

I am trying to have my perl script get an Xxml file from online and validate it according to an XSD file.

The code to do this is as follows:

my $url = shift @ARGV;
my $response = $ua->get($url) || die "Can't fetch file";
my $file = $response->content;

my $schema_file = "schema.xsd";
my $schema = XML::LibXML::Schema->new(location => $schema_file);
my $parser = XML::LibXML->new;
my $doc    = $parser->parse_string($file);
eval { $schema->validate($doc) };
die $@ if $@;

Running this results in a cryptic error: "Element cropdata content check failure" (cropdata is the first of my nonroot tags).

In my XSD file, the entry looks like:

<xs:element name="cropdata">
<xs:complexType>
<xs:sequence>

Then a bunch of "<xs:element..../>" and then:

</xs:sequence>
</xs:complexType>
</xs:element>

Going into the perl debugger shows that after letting the line "my $doc = $parser->parse_string($file);" run, $doc prints as XML::LibXML::Document=SCALAR(0x6b99f0).

Can anyone help me shed light on what I am doing wrong? (Warning: it may be a dumb mistake, I wouldn't put it past myself).

回答1:

Turns out that the sample xml file I had been provided was invalid, and lo and behold, upon checking and correcting it in xmllint, everything works.