Your code is messy. Your script begins with a line which is intended to be the shebang line but is not. You re-define two variables in this short script. You check if validation failed and merrily go on your way even if it did. These are likely not the cause of your problems, but they do make diagnosing the problem harder. I tried to refactor your code. The code below passes perl -c
. Further, I tried it using sample XML
and XSD
files. As explained on that page, with a missing element, validation failed. When the missing information was added, validation succeeded and expected output was produced.
#!/usr/bin/env perl
use strict; use warnings;
use XML::LibXML;
use XML::DOM;
my $xml = 'Export.xml';
my $xsd = 'export.xsd';
if ( my $error = validate_xml_against_xsd($xml, $xsd) ) {
die "Validation failed: $error
";
}
my @offerings = get_product_offerings( $xml );
print "$_
" for @offerings;
sub get_product_offerings {
my ($xml) = @_;
my $parser = XML::DOM::Parser->new;
my $doc = $parser->parsefile($xml);
my $nodes = $doc->getElementsByTagName("book")->item(0);
return map {
$_->getNodeType == ELEMENT_NODE
? $_->getNodeName
: ()
} $nodes->getChildNodes;
}
sub validate_xml_against_xsd {
my ($xml, $xsd) = @_;
my $schema = XML::LibXML::Schema->new(location => $xsd);
my $parser = XML::LibXML->new;
my $doc = $parser->parse_file($xml);
eval { $schema->validate( $doc ) };
if ( my $ex = $@ ) {
return $ex;
}
return;
}
Output:
author
title
genre
price
pub_date
review
By the way, the error message when validation failed was informative: Validation failed: Element 'review': This element is not expected. Expected is (pub_date ).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…