I am pretty sure that this won’t be an eye-opener for many, but I just had my eureka moment with XPath. I have been playing with XML config file for a light-weight survey module for our intranet and has been banging my head against Perl XML::Simple module. After a lot of sweat and tears, mismatches between hash and array return values I thought of XPath (probably thanks to SteveY’s post) — and I was amazed how much simpler things became!
Instead of custom-building querying logic, all I now need to do to fetch a survey question or any of survey answers is:
use XML::XPath; use XML::XPath::XMLParser; my $xp = XML::XPath->new(filename => 'survey.xml'); # first survey description print $xp->getvalue('/surveys/survey/description'),"n"; # second question of the third survey print $xp->getvalue('/surveys/survey/questions/q'),"n"; # fourth answer to that print $xp->getvalue('/surveys/survey/answers/for[@qid=2]/a'),"n";
I am sure that XML::Simple has its uses as well — but certainly for querying data XML::XPath just soooo much easier!