libxml2 - Perl libXML find node by attribute value -


i have large xml document iterating through. xml's use attributes rather node values. may need find numerous nodes in file piece 1 grouping of information. tied via different ref tag values. each time need locate 1 of nodes extract data looping through entire xml , doing match on attribute find correct node. there more efficient way select node of given attribute value instead of looping , compare? current code slow useless.

currently doing numerous times in same file numerous different nodes , attribute combinations.

my $searchid = "1234"; foreach $nodes ($xc->findnodes('/plm:plmxml/plm:externalfile')) {     $id      = $nodes->findvalue('@id');     $file    = $nodes->findvalue('@locationref');     if ( $searchid eq $id ) {         print "the file name = $file\n";     } } 

in above example looping , using "if" compare id match. hoping below match node attribute instead... , more efficient looping?

my $searchid = "1234"; $nodes = ($xc->findnodes('/plm:plmxml/plm:externalfile[@id=$searchid]')); $file    = $nodes->findvalue('@locationref'); print "the file name = $file\n"; 

if doing lots of ids, ikegami's answer worth reading.

i hoping below match node attribute instead

...

$nodes = ($xc->findnodes('/plm:plmxml/plm:externalfile[@id=$searchid]')); 

sort of.

for given id, yes, can

$nodes = $xc->findnodes("/plm:plmxml/plm:externalfile[\@id=$searchid]"); 

... provided $searchid known numeric. notice double quotes in perl means variables interpolate, should escape @id because part of literal string, not perl array, whereas want value of $searchid become part of xpath string, not escaped.

note in case asking in scalar context have xml::libxml::nodelist object, not actual node, nor arrayref; latter need use square brackets instead of round ones have done in next example.

alternatively, if search id may not numeric know sure safe put in xpath string (e.g. doesn't have quotes), can following:

$nodes = [ $xc->findnodes('/plm:plmxml/plm:externalfile[@id="' . $searchid . '"]') ]; print $nodes->[0]->getattribute('locationref'); # if you're 100% sure exists 

notice here resulting string enclose value in quotation marks.

finally, possible skip straight to:

print $xc->findvalue('/plm:plmxml/plm:externalfile[@id="' . $searchid . '"]/@locationref'); 

... providing know there 1 node id.


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -