简体   繁体   English

使用LibXML验证XML

[英]Validate XML using LibXML

Currently, I am using the XML::LibXML perl module to validate an XML file against a defined XML schema. 目前,我使用XML :: LibXML perl模块根据定义的XML模式验证XML文件。 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. 目前,如果我的XML文件无法针对定义的XML Schema成功验证,我将得到一个错误列表通知我,例如某些元素不是预期的,然后是预期的。 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. 在我的XML文件中,我将有许多相同名称的元素,但它们可能嵌套在XML文件的不同位置。

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? 我的问题是,无论如何,我可以在尝试执行验证时输出可能出错的任何元素的XPath位置吗?

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. 目前,我的XML文件非常庞大,并且在验证失败时很难“调试”它,因为错误中显示的元素的名称可能会在XML文件的不同位置多次出现。

My code is below for using LibXML to validate an XML file against a schema. 我的代码如下所示,使用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";

I have just stumbled on the same problem and found that the XML parser does not store the line numbers by default . 我偶然发现了同样的问题,发现XML解析器默认不存储行号。 But you can tell him to do so with the XML_LIBXML_LINENUMBERS parameter of the constructor. 但您可以使用构造函数的XML_LIBXML_LINENUMBERS参数告诉他这样做。

The following script will tell actual line numbers for errors instead of 0 以下脚本将告知实际行号而不是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';

您可能需要查看: XML :: Validate以获取行号和列号?

See source of Padre::Task::SyntaxChecker::XML . 请参阅Padre :: Task :: SyntaxChecker :: XML的源代码。 This module is used by Padre IDE to do syntax check of XML file. Padre IDE使用此模块对XML文件进行语法检查。 See also t/01-valid.t in Padre-Plugin-XML distribution for an example of usage including line numbers. 另请参阅Padre-Plugin-XML发行版中的t / 01-valid.t以获取包括行号在内的用法示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM