in reply to Re^6: Xpath value query
in thread Xpath value query

This was one problem, you don't need to my $xpath = "q!" . $argvalx . "!";

see http://perldoc.perl.org/perlop.html#Quote-Like-Operators

and the second XPATH was missing a [] here [@tc="8"]].
Assuming you will only get a single match try

#!perl use strict; use XML::Twig::XPath; my $xmlfile = $ARGV[0] || 'txlife.xml'; my $twig = XML::Twig::XPath->new(); $twig->parsefile($xmlfile); my $root = $twig->root; my @XPV = (); $XPV[0] = '//Party[@id=//Relation[child::RelationRoleCode[@tc="37"]]/@ +RelatedObjectID]/Producer/CarrierAppointment/CompanyProducerID'; $XPV[1] = '//OLifE/Party[@id=//OLifE/Relation[RelationRoleCode[@tc=8]] +/@RelatedObjectID]/Person/FirstName'; for my $i (0..1){ my ($name,$value) = get_xpath_value($XPV[$i]); print " $name : $value\n"; } sub get_xpath_value { my ($xpath) = @_; my @nodes = $root->findnodes($xpath); my $value = $nodes[0]->text; my $name = $nodes[0]->getName; return ($name,$value); }
Update : added getName and simplified
poj

Replies are listed 'Best First'.
Re^8: Xpath value query
by SDwerner (Initiate) on Sep 18, 2015 at 18:44 UTC

    My most humble thanks.. I think that get's me exactly what I need to make this work.

    What I don't understand I guess is why in the original example you surrounded the XPath string with the q!..!? Just curious, I realize it doesn't matter with this solution.

    again, thanks.

      because you had single quotes in [@tc='37'] in the query I couldn't just use ' query '.

        OK, so one more problem I don't understand.. and I think it's more my lack of understanding about HASHES. I was getting an error on the my $value = $nodes[0]->text; statement indicating Can't call method "text" on an undefined. So, I thought I could use if (@node[0]) { my $value = $nodes[0]->text; } else { $value = "EMPTY_STRING"; } but now everything comes back as if the variable is undefined. How do I determine if a hash is undefined?

        That makes sense now..