Validating XML with LibXML

I am currently using the perl XML :: LibXML module to validate an XML file against a specific XML schema. At the moment, if my XML file cannot successfully check for compliance with a specific XML schema, I will get a list of errors telling me, for example, that some elements were not expected and then expected. In my XML file, I will have many elements with the same name, but they can be nested in different places in the XML file.

My question is, is there anyway when I can infer the XPath location of any elements that may occur when trying to validate?

My XML file is currently quite large and difficult to debug when validation fails because the name of the element displayed in the error can occur many times in different places in the XML file.

My code below is for using LibXML to validate an XML file for 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"; 
+6
xml validation perl libxml2
source share
3 answers

I just stumbled upon the same problem and found that the XML parser does not store default line numbers. But you can tell him to do this with the XML_LIBXML_LINENUMBERS constructor parameter.

The following script will show 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'; 
+3
source share

You can look: XML :: Validate to get row number and column number?

+2
source share

See Padre :: Task :: SyntaxChecker :: XML source. This module is used by the Padre IDE to check the syntax of an XML file. See Also t / 01-valid.t in the Padre-Plugin-XML distribution for usage examples, including line numbers.

0
source share

All Articles