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...
Why not create triplets (XPath, char content, order number) instead of just pairs?
Re:Triplets!
acme on 2003-03-31T13:07:27
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...