Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

acme (189)

  (email not shown publicly)

Leon Brocard (aka acme) is an orange-loving Perl eurohacker with many varied contributions to the Perl community, including the GraphViz module on the CPAN. YAPC::Europe was all his fault. He is still looking for a Perl Monger group he can start which begins with the letter 'D'.

Journal of acme (189)

Monday March 31, 2003
04:33 AM

XPath sorting

[ #11331 ]
For some reason I've ended up with a list of (xpath, char content) pairs for every node in an XML document and need to recreate the original document using these. This is easy, I can sort it alphabetically and then create the nodes in the right order. Apart from annoying /foo/bar[1]/quux, /foo/bar[2]/quux, ..., /foo/bar[10]/quux not sorting in the right order. I currently work around it as in the code below. Is there an other way I could do this? It seems a little hacky to have to change them all to /foo/bar/[00004]/quux to sort it...

sub xpath_sort {
  my($self, @xpaths) = @_;
  my %canon;
  foreach my $xpath (@xpaths) {
    my $c = $xpath;
    $c =~ s{\[(\d+)\]}{'[' . sprintf("%05d", $1) . ']'}e;
    $canon{$xpath} = $c;
  @xpaths = sort { $canon{$a} cmp $canon{$b} } @xpaths;
  return @xpaths;

XPath rocks. I can't imagine XML without it anymore...

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • Why not create triplets (XPath, char content, order number) instead of just pairs?

    • That's an option. But if I change the tree, I'd have to update the order as well, which sounds like a bit of a pain. It's just a shame that sorting the XPath almost works.
  • I don't think there's a solution to your problem, apart from having a way of creating the nodes not in order (and using ghost nodes) which would be a great thing to have.

    XPath rocks. I can't imagine XML without it anymore...

    Be careful... you're getting very dangerously close to liking XSLT...


    -- Robin Berjon []