drfrog has asked for the wisdom of the Perl Monks concerning the following question:

hey!
again i pray to thee!

im looking to parse an xml and test the dtd for its validity

here is the code snippet:
#!/usr/bin/perl use XML::LibXML; my $parser = XML::LibXML->new(); $parser->validation(1); my $doc = $parser->parse_string(<<'EOT'); <?xml version="1.0"?> <!DOCTYPE airg SYSTEM "thedtd.dtd"> <xml/> EOT print $doc->is_valid eq 1?"is cool\n":"error\n";
which is great!
it tell me if its ok or not, but that doesnt report where/when/how its failing!
can anyone recommend how to retrieve that sort of info (even if i need to use another module!)?
  • Comment on using XML::LIbXML to validate against a dtd and retrieve any errors therein
  • Download Code

Replies are listed 'Best First'.
Re: using XML::LIbXML to validate against a dtd and retrieve any errors therein
by Matts (Deacon) on May 18, 2002 at 07:17 UTC
    This is untested, but try:
    print XML::LibXML->get_last_error;
    Or alternatively, use the exception throwing form of validation:
    eval { $doc->validate; }; if ($@) { print "Doc not valid: $@\n"; } else { print "Doc valid\n"; }
      hello
      i figured this out!
      while i couldnt find anything about the validate or
      get_last _error functions i did manage to get code to werk!

      thanks matt!

      here is a sample xml:
      <?xml version="1.0"?> <!DOCTYPE roots SYSTEM 'dtd.dtd'> <roots> <child1 attrib="3"></child1> <child2></child2> <child3/> </roots>
      the dtd:
      <!ELEMENT roots (child1,child2,child3)> <!ELEMENT child1 (#PCDATA)> <!ATTLIST child1 attrib CDATA #REQUIRED> <!ELEMENT child2 EMPTY> <!ELEMENT child3 (#PCDATA)>
      and the perl script:
      #!/usr/bin/perl use strict; use XML::LibXML; my $parser = XML::LibXML->new(); $parser->validation(1); eval {print "xml is valid=".$parser->parse_file('xml.xml')->is_valid +."\n"; }; if ($@) { print "dtd not valid: $@\n";} else { print "dtd valid\n";}

      hope this helps anyone else in the future