olaloux,
many thanks for your reply, your example was complete, but it is not quite what i asked for, the xml i am processing will not have the dtd definition i must specify with Libxml what one to use.
hence if you change your input xml to:
<?xml version="1.0" encoding="ISO-8859-1"?>
<countrieslist>
<countries count="2">
<country id="1234">
<name>
<en>Italy</en>
<fr>Italie</fr>
</name>
</country>
<country id="7890">
<name>
<en>Spain</en>
<fr>Espagne</fr>
</name>
</country>
</countries>
</countrieslist>
how do i get libxml to parse it then?
many thanks
Peewee
Main Topics
Browse All Topics





by: olalouxPosted on 2002-10-14 at 01:03:00ID: 7332439
Take a good inhabit: put a reference to the DTD in the XML file, even if you don't want to put all the DTD there.
d">
no(STDIN), "r")) { h($fileHan dler);
The sample I'll give to you show how you can validate an XML with XML::LibXML:
First: the DTD (an external one as you wished):
<!ELEMENT countrieslist (countries)>
<!ELEMENT countries (country*)>
<!ATTLIST countries count CDATA #REQUIRED>
<!ELEMENT country (name)>
<!ATTLIST country id CDATA #REQUIRED>
<!ELEMENT name (en, fr)>
<!ELEMENT en (#PCDATA)>
<!ELEMENT fr (#PCDATA)>
Second: the XML you want to validate:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE countrieslist SYSTEM "/dtdpath/countrieslist.dt
<countrieslist>
<countries count="2">
<country id="1234">
<name>
<en>Italy</en>
<fr>Italie</fr>
</name>
</country>
<country id="7890">
<name>
<en>Spain</en>
<fr>Espagne</fr>
</name>
</country>
</countries>
</countrieslist>
Third: the Perl code to validate this XML with this external DTD ;-)
use strict;
use XML::LibXML;
use IO::Handle;
# Create a new parser
my $parser=new XML::LibXML;
$parser->validation(1);
$parser->recover(1);
# Let's start the parsing
my $fileHandler=new IO::Handle;
my $document;
if ($fileHandler->fdopen(file
eval { # Try to parse
$document=$parser->parse_f
};
if ($@ eq '') { # The $@ could contain the error
print "XML valid.\n";
} else {
print "XML not valid 'cause of $@ !\n";
}
$fileHandler->close;
}
To test that:
perl -d script.pl < xml.xml