Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1146477]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2026-02-13 12:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.