http://qs321.pair.com?node_id=534193

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

Monks,

I wanna extract specific elements from the xml file (Example: h1/title). I have tried using XML:XPATH as follows:

my $str = $ARGV[0]; my $xp = XML::XPath->new(xml => "$str"); my $nodeset = $xp->find('//h1/title'); # foreach my $node ($nodeset->get_nodelist) {my $tag=XML::XPath::XMLParser::as_string($node); print "$tag\n";}

I got parsing error b'cos of entities. Hence i've replaced all the entities with some other characters and after extracting all the tags i've replaced back the original entites. I got the result which i need.

I'm sure that there is a better way to do this. Could u pls suggest me the better way?

Cheers

--C

Update:

sample xml file

<xml> <h1><title>TH&Eacute;MATIC INTRODUCTION</title> <p>Para goes here</p> <h2><title>Sub level title</title> <p>Para Text</p></h2> </h1></xml>

Error:

undefined entity at line 2, column 13, byte 19: <xml> <h1><title>TH&Eacute;MATIC INTRODUCTION</title> ============^ <p>Para goes here</p> <h2><title>Sub level title</title> at c:/Perl/site/lib/XML/Parser.pm line 187

Perl code

use XML::Parser; use XML::Parser::Expat; use XML::Twig; use XML::XPath; undef $/; $file = $ARGV[0]; open (IN, "<$file"); $xml = <IN>; my $xp = XML::XPath->new(xml => "$xml"); my $nodeset = $xp->find('//h1/title'); # foreach my $node ($nodeset->get_nodelist) { my $tag=XML::XPath::XMLParser::as_string($node); print "$tag\n"; }