I have attached the complete patch including tests now as a file since
copy & paste causes trouble.
diff -rupN HTML-Selector-XPath-0.04/lib/HTML/Selector/XPath.pm HTML-Selector-XPath-0.04-JZOBEL/lib/HTML/Selector/XPath.pm
--- HTML-Selector-XPath-0.04/lib/HTML/Selector/XPath.pm 2010-02-27 10:44:04.000000000 +0100
+++ HTML-Selector-XPath-0.04-JZOBEL/lib/HTML/Selector/XPath.pm 2010-05-22 14:39:02.000000000 +0200
@@ -11,7 +11,7 @@ our @EXPORT_OK = qw(selector_to_xpath);
use Carp;
sub selector_to_xpath {
- __PACKAGE__->new(shift)->to_xpath;
+ __PACKAGE__->new(shift)->to_xpath(@_);
}
my $reg = {
@@ -44,9 +44,11 @@ sub selector {
sub to_xpath {
my $self = shift;
my $rule = $self->{expression} or return;
+ my %parms = @_;
+ my $root = $parms{root} || '/';
my $index = 1;
- my @parts = ("//", "*");
+ my @parts = ("$root/", "*");
my $last_rule = '';
my @next_parts;
@@ -144,7 +146,7 @@ sub to_xpath {
# Match commas
if ($rule =~ s/$reg->{comma}//) {
- push @parts, " | ", "//", "*"; # ending one rule and beginning another
+ push @parts, " | ", "$root/", "*"; # ending one rule and beginning another
$index = @parts - 1;
}
}
diff -rupN HTML-Selector-XPath-0.04/t/03_xpath_root.t HTML-Selector-XPath-0.04-JZOBEL/t/03_xpath_root.t
--- HTML-Selector-XPath-0.04/t/03_xpath_root.t 1970-01-01 01:00:00.000000000 +0100
+++ HTML-Selector-XPath-0.04-JZOBEL/t/03_xpath_root.t 2010-05-22 15:07:31.000000000 +0200
@@ -0,0 +1,68 @@
+use strict;
+use Test::Base;
+use HTML::Selector::XPath qw(selector_to_xpath);
+
+plan tests => 1 * blocks;
+filters { selector => 'chomp', xpath => 'chomp' };
+
+run {
+ my $block = shift;
+ is selector_to_xpath($block->selector, root=> '/R/'), $block->xpath, $block->selector;
+}
+
+__END__
+===
+--- selector
+*
+--- xpath
+/R//*
+
+===
+--- selector
+E
+--- xpath
+/R//E
+
+===
+--- selector
+E F
+--- xpath
+/R//E//F
+
+===
+--- selector
+E > F
+--- xpath
+/R//E/F
+
+===
+--- selector
+E + F
+--- xpath
+/R//E/following-sibling::*[1]/self::F
+
+===
+--- selector
+E[foo]
+--- xpath
+/R//E[@foo]
+
+===
+--- selector
+E[foo="warning"]
+--- xpath
+/R//E[@foo='warning']
+
+===
+--- selector
+E#myid
+--- xpath
+/R//E[@id='myid']
+
+===
+--- selector
+foo.bar, bar
+--- xpath
+/R//foo[contains(concat(' ', @class, ' '), ' bar ')] | /R//bar
+
+