1

I have an xml something like

<Screen>
    <window name="gui">
        <widget name="status" pos="0:0">
            <timedate name="timedate"/>
            <message name="message"/>
        </widget>
    </window>
</Screen>

One good thing about this xml is that every node has unique name. It will not repeat anywhere in the xml.

To find a node, I can query using xpath and will get the result for its presence/absence, But I need to find the path traversed.

example I can search the timedate node using xpath query '//timedate', but along with this I also need the path traversed i.e. Screen/window/widget/timedate.

Please suggest me some ways to retrieve the path also.

Your help will be highly appreciated.

rpg
  • 1,632
  • 2
  • 18
  • 34
  • ancestor-or-self::timedate -- this axis gives you the way from the element to the document element.. I am not that sure if the expression is right as it is but the axis is. If you can get a ordered list you should get a result beginning at the root going down to the the path than becomes somthing like list.join('/'), but that is javascript like, I do not know perl – philipp Jan 03 '13 at 14:05

3 Answers3

1

See this answer for a full solution: https://stackoverflow.com/a/4747858/36305.

While the solution is in XSLT, the code can be converted to any other programming language, if necessary.

Community
  • 1
  • 1
Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
  • great solution, and thanks for your prompt reply. But this time, I was looking something in Perl itself. I wish I could also mark this answer as accepted too :) – rpg Jan 07 '13 at 06:06
1

That exact details depend on what module you use to process XML. For example, in XML::XSH2, you can use the pwd command.

A more verbose XML::LibXML example:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw(say);

use XML::LibXML;

my $x = XML::LibXML->load_xml(location => 'example.xml');
my $n = $x->find('//timedate')->shift;
say $n->nodePath;
choroba
  • 231,213
  • 25
  • 204
  • 289
0

CPAN has a tool for that, xpathify, which itself is a part of the HTML::Untemplate package:

screenshot

creaktive
  • 5,193
  • 2
  • 18
  • 32