问题描述
当前,我正在使用XML :: LibXML perl模块根据定义的XML模式验证XML文件.此刻,如果我的XML文件未能针对定义的XML Schema成功验证,我将得到一系列错误通知我,例如,某些元素不是预期的,然后是预期的.在我的XML文件中,我将有许多同名的元素,但它们可能嵌套在XML文件中的不同位置.
我的问题是,无论如何,我可以输出尝试执行验证时可能出错的任何元素的XPath位置吗?
当前,我的XML文件很大,验证失败时很难对其进行调试",因为错误中显示的元素名称可能在XML文件的不同位置多次出现. >
下面是我的代码,用于使用LibXML根据模式验证XML文件.
#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my $schema_file = 'MySchema.xml';
my $document = 'MyFile.xml';
my $schema = XML::LibXML::Schema->new(location => $schema_file);
my $parser = XML::LibXML->new;
my $doc = $parser->parse_file($document);
eval { $schema->validate($doc) };
die $@ if $@;
print "$document validated successfully\n";
我偶然发现了相同的问题,发现XML解析器默认不存储行号 .但是您可以使用构造函数的XML_LIBXML_LINENUMBERS
参数告诉他这样做.
以下脚本将告诉实际的行号以显示错误,而不是0
use Modern::Perl;
use XML::LibXML;
my ($instance, $schema) = @ARGV;
my $doc = XML::LibXML->new(XML_LIBXML_LINENUMBERS => 1)->parse_file($instance);
my $xmlschema = XML::LibXML::Schema->new( location => $schema );
my $res = eval { $xmlschema->validate( $doc ); };
say "error: $@" if $@;
say "res: ", $res//'undef';
Currently, I am using the XML::LibXML perl module to validate an XML file against a defined XML schema. At the moment, if my XML file fails to validate successfully against the defined XML Schema, I will get a list of errors informing me, for example that certain elements were not expected and then what was expected instead. In my XML file I will have many elements of the same name but they may be nested in various places in the XML file.
My question is, is there anyway in which I can output the XPath location of any elements that may error when attempting to perform the validation?
Currently, my XML file is quite big and it is hard to "debug" it when validation fails as the name of the element that is displayed in the error, may occur many times in various places in the XML file.
My code is below for using LibXML to validate an XML file against a schema.
#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my $schema_file = 'MySchema.xml';
my $document = 'MyFile.xml';
my $schema = XML::LibXML::Schema->new(location => $schema_file);
my $parser = XML::LibXML->new;
my $doc = $parser->parse_file($document);
eval { $schema->validate($doc) };
die $@ if $@;
print "$document validated successfully\n";
I have just stumbled on the same problem and found that the XML parser does not store the line numbers by default. But you can tell him to do so with the XML_LIBXML_LINENUMBERS
parameter of the constructor.
The following script will tell actual line numbers for errors instead of 0
use Modern::Perl;
use XML::LibXML;
my ($instance, $schema) = @ARGV;
my $doc = XML::LibXML->new(XML_LIBXML_LINENUMBERS => 1)->parse_file($instance);
my $xmlschema = XML::LibXML::Schema->new( location => $schema );
my $res = eval { $xmlschema->validate( $doc ); };
say "error: $@" if $@;
say "res: ", $res//'undef';
这篇关于使用LibXML验证XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!