Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: How can I browse & list XPATH of a XML Message?

by Preceptor (Deacon)
on Oct 30, 2015 at 10:45 UTC ( [id://1146477] : note . print w/replies, xml ) Need Help??


in reply to How can I browse & list XPATH of a XML Message?

I got as far as this using "XML::Twig":

#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use XML::Twig; my $twig = XML::Twig->parse( \*DATA ); print $twig ->get_xpath( '/root/fish/carrot[@colour="orange"]/pie', 0 +)->text, "\n"; foreach my $node ( $twig->get_xpath('//*') ) { my @path_tags; my @path_with_att; my $cursor = $node; while ($cursor) { unshift( @path_tags, $cursor->tag ); my $att_path = ""; if ( $cursor->atts ) { $att_path = join( "", map { "[@" . $_ . "=\"" . $cursor->att($_) . "\"]" } keys %{ $cursor->atts } ); } unshift( @path_with_att, $cursor->tag . $att_path ); $cursor = $cursor->parent; } print join( "/", @path_tags ), "\n"; my $xpath_with_atts = "/" . join( "/", @path_with_att ); print $xpath_with_atts, "\n"; print "Found:", $twig->get_xpath( $xpath_with_atts, 0 )->tag, "\n" +; } __DATA__ <root> <fish skin="scaly" home="pond"> <carrot colour="orange"> <pie>This value</pie> </carrot> </fish> </root>

It doesn't quite do what you want, unfortunately, as what it doesn't do is give you the numeric index of the node, and so whilst the XPATH is valid, it's not necessarily unique.

I'm going to try and think if there's a good way to do what you're wanting.

Replies are listed 'Best First'.
Re^2: How can I browse & list XPATH of a XML Message?
by ambrus (Abbot) on Oct 30, 2015 at 20:06 UTC

    I suggest that you use the ->xpath method of the elements to find the path together with the numeric indexes. Eg.

    my $xpath_with_atts = $node->xpath;