XML-XQL-0.68/0040755000076500007650000000000007611625246013016 5ustar tjmathertjmatherXML-XQL-0.68/t/0040755000076500007650000000000007611625246013261 5ustar tjmathertjmatherXML-XQL-0.68/t/xql_test_DATA_CKL.t0100644000076500007650000000367706777462711016615 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); #@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('//.[attribute()!count() = 1]', $doc); # err @result = XML::XQL::solve ('DATA/CKL[attribute(2, 1)!count() = 1]', $doc); #@result = XML::XQL::solve ('//.[false()!textNode() = 1]', $doc); #@result = XML::XQL::solve ('//.[.!value() $blue$ date("1993/02/14")]', $doc); #?@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); @result = XML::XQL::solve ('DATA/CKL', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
XML-XQL-0.68/t/xql_recurse.t0100644000076500007650000000230306777462705016010 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < a.a.b.b a.a.b.b2 a.a.b2.b a.a.b2.b2 END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('//b//b', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ a.a.b.b a.a.b.b2 a.a.b2.b a.a.b2.b2 XML-XQL-0.68/t/xql_sin2.t0100644000076500007650000000213206777462706015214 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1 2 3 4 END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('sin(DATA/*)', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ 0.841470984807897 0.909297426825682 0.141120008059867 -0.756802495307928 XML-XQL-0.68/t/xql_new.t0100644000076500007650000000324406777462703015134 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Date; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); #@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('//.[attribute()!count() = 1]', $doc); # err @result = XML::XQL::solve ('DATA/CKL[attribute(2, 1)!count() = 1]', $doc); #@result = XML::XQL::solve ('//.[false()!textNode() = 1]', $doc); # #?@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('DATA/CKL', $doc); # # new ("Date", STRING) should return the same thing as date(STRING) @result = XML::XQL::solve ('DATA//*[. = new("Date", "1993/02/14")]', $doc); $result = XML::XQL::Debug::str (\@result); assert_output ($result); #print $result; __DATA__ 1993-02-14 XML-XQL-0.68/t/xql_eval.t0100644000076500007650000000217006777462701015265 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('eval ("3 + 4", "Number")', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ 7 XML-XQL-0.68/t/xql_map.t0100644000076500007650000000237706777462703015126 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('map (DATA/CKL/@cklAttr, "s/[Aa]/Z/g; $_")', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ cklAttr="cklZttrVZl1" cklAttr="cklZttrVZl2" XML-XQL-0.68/t/xql_comment.t0100644000076500007650000000331406777462677016015 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('//comment()', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ XML-XQL-0.68/t/xql_parent.t0100644000076500007650000000206307044153545015617 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < c1 c2 END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('doc/a/b/c[@attr="foo"]/..', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ c1 c2 XML-XQL-0.68/t/xql_union.t0100644000076500007650000000330606777462712015472 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $doc = $dom->parsefile (XML::XQL::Debug::filename("samples/bookstore.xml")); assert_ok ($doc); @result = XML::XQL::solve ('bookstore/book/(title | author/first-name | price)', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ Seven Years in Trenton Joe 12 History of Trenton Mary 55 Trenton Today, Trenton Tomorrow Toni 6.50 XML-XQL-0.68/t/xql_document.t0100644000076500007650000000210707014353240016132 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('document (doc/file/@name)/root', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ Entity ref gen_ent in text XML-XQL-0.68/t/xql_subscript2.t0100644000076500007650000000165406777462707016452 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1 2 3 4 END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('//x/y[0]', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ 1 3 XML-XQL-0.68/t/xql_recurse2.t0100644000076500007650000000205406777462705016075 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('x//y[0]', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ XML-XQL-0.68/t/xql_index2.t0100644000076500007650000000166606777462702015541 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1 2 3 4 END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('//x/y[index() = 0]', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ 1 3 XML-XQL-0.68/t/xql_cos.t0100644000076500007650000000222206777462700015117 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 1 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('DATA/*[. = cos(0)]', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ 1 XML-XQL-0.68/t/attr3.xml0100644000076500007650000000063507314123352015030 0ustar tjmathertjmather ]> Entity ref &ent; in text XML-XQL-0.68/t/xql_Strict.t0100644000076500007650000000370706777462676015630 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL::Strict; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); #@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('//.[attribute()!count() = 1]', $doc); # err @result = XML::XQL::solve ('DATA/CKL[attribute(2, 1)!count() = 1]', $doc); #@result = XML::XQL::solve ('//.[false()!textNode() = 1]', $doc); #@result = XML::XQL::solve ('//.[.!value() $blue$ date("1993/02/14")]', $doc); #?@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); @result = XML::XQL::solve ('DATA/CKL', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
XML-XQL-0.68/t/xql_attr.t0100644000076500007650000000332206777462676015323 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('//.[attribute()!count() = 1]', $doc); # err @result = XML::XQL::solve ('DATA/CKL[attribute(2, 1)!count() = 1]', $doc); #@result = XML::XQL::solve ('//.[false()!textNode() = 1]', $doc); # #?@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('DATA/CKL', $doc); #@result = XML::XQL::solve ('//.[.!value() = date("1993/02/14")]', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ 0002 USA
45 HOLOMOA STREET
XML-XQL-0.68/t/xql_once.t0100644000076500007650000000303107044157166015251 0ustar tjmathertjmatherBEGIN {print "1..5\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 1 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); my $counter = 0; sub incr_counter { my ($context, $list, $expr) = @_; $counter++; $expr->solve ($context, $list); } XML::XQL::defineFunction ("incr", \&incr_counter, 1, 1, 0); # incr is evaluated 4 times @result = XML::XQL::solve ('DATA/*[. = incr(cos(0))]', $doc); assert_ok ($counter == 4); $counter = 0; # incr is evaluated only once @result = XML::XQL::solve ('DATA/*[. = once(incr(cos(0)))]', $doc); assert_ok ($counter == 1); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ 1 XML-XQL-0.68/t/xql_big.t0100644000076500007650000000716307222704656015100 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $doc = $dom->parsefile (XML::XQL::Debug::filename("samples/REC-xml-19980210.xml")); assert_ok ($doc); @result = XML::XQL::solve ('//p[termdef =~ "/entit/"]//prod', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ Char #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. EntityDecl GEDecl | PEDecl GEDecl '<!ENTITY' S Name S EntityDef S? '>' PEDecl '<!ENTITY' S '%' S Name S PEDef S? '>' EntityDef EntityValue | (ExternalID NDataDecl?) PEDef EntityValue | ExternalID ExternalID 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral NDataDecl S 'NDATA' S Name NotationDecl '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' PublicID 'PUBLIC' S PubidLiteral XML-XQL-0.68/t/xql_template.t0100644000076500007650000000202306777462710016146 0ustar tjmathertjmatherBEGIN {print "1..2\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('DATA/CKL', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; #assert_output ($result); __DATA__ XML-XQL-0.68/t/xql_date.t0100644000076500007650000000313106777462700015250 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Date; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); #@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('//.[attribute()!count() = 1]', $doc); # err @result = XML::XQL::solve ('DATA/CKL[attribute(2, 1)!count() = 1]', $doc); #@result = XML::XQL::solve ('//.[false()!textNode() = 1]', $doc); # #?@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('DATA/CKL', $doc); # @result = XML::XQL::solve ('DATA//*[. = date("1993/02/14")]', $doc); $result = XML::XQL::Debug::str (\@result); assert_output ($result); #print $result; __DATA__ 1993-02-14 XML-XQL-0.68/t/xql_precedes.t0100644000076500007650000000261306777462704016135 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < MARCELLUS Tis gone! Exit Ghost We do it wrong, being so majestical, To offer it the show of violence; For it is, as the air, invulnerable, And our vain blows malicious mockery. END my $doc = $dom->parse ($str); assert_ok ($doc); #@result = XML::XQL::solve ('SPEECH//(SPEAKER ;; LINE)', $doc); @result = XML::XQL::solve ('SPEECH//(SPEAKER ;; LINE ; STAGEDIR = "Exit Ghost")', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ MARCELLUS Tis gone! Exit Ghost XML-XQL-0.68/t/xql_union2.t0100644000076500007650000000352406777462712015556 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $doc = $dom->parsefile (XML::XQL::Debug::filename("samples/bookstore.xml")); assert_ok ($doc); @result = XML::XQL::solve ('//book/(@style | title | price | price/@exchange | price/@intl)', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ style="autobiography" Seven Years in Trenton 12 style="textbook" History of Trenton 55 style="novel" Trenton Today, Trenton Tomorrow 6.50 intl="canada" exchange="0.7" XML-XQL-0.68/t/attr2.xml0100644000076500007650000000044507314123333015025 0ustar tjmathertjmather ]> XML-XQL-0.68/t/xql_index.t0100644000076500007650000000246206777462702015452 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < book 1 mag 1 book 2 book 3 mag 2 book 4 mag 3 mag 4 book 5 END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('library/book[index() < 4]', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ book 1 book 2 book 3 book 4 XML-XQL-0.68/t/xql_subst.t0100644000076500007650000000240106777462707015501 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('subst (DATA/CKL/@cklAttr, "[Aa]", "Z", "g")', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ cklAttr="cklZttrVZl1" cklAttr="cklZttrVZl2" XML-XQL-0.68/t/xql_text.t0100644000076500007650000000174206777462711015327 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < It is It is medium0 in high0 nodehigh0 It is high 1 END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('/highest/high!text(0)', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ It is high0 It is high 1 XML-XQL-0.68/t/xql_test.t0100644000076500007650000000367706777462710015332 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < 1993-02-14 P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
END my $doc = $dom->parse ($str); assert_ok ($doc); #@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); #@result = XML::XQL::solve ('//.[attribute()!count() = 1]', $doc); # err @result = XML::XQL::solve ('DATA/CKL[attribute(2, 1)!count() = 1]', $doc); #@result = XML::XQL::solve ('//.[false()!textNode() = 1]', $doc); #@result = XML::XQL::solve ('//.[.!value() $blue$ date("1993/02/14")]', $doc); #?@result = XML::XQL::solve ('DATA/CKL[@cklAttr $eq$ "cklAttrVal2"]', $doc); @result = XML::XQL::solve ('DATA/CKL', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ P001 USA
HNLLHIWP
0002 USA
45 HOLOMOA STREET
XML-XQL-0.68/t/xql_immed_precedes.t0100644000076500007650000000204706777462701017306 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < Shady Grove Aeolian Over the River, Charlie Dorian END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('//(TD="Shady Grove" ; TD)', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ Shady Grove Aeolian XML-XQL-0.68/t/xql_subscript.t0100644000076500007650000000302306777462706016357 0ustar tjmathertjmatherBEGIN {print "1..3\n";} END {print "not ok 1\n" unless $loaded;} use XML::XQL; use XML::XQL::DOM; use XML::XQL::Debug; $loaded = 1; print "ok 1\n"; my $test = 1; sub assert_ok { my $ok = shift; print "not " unless $ok; ++$test; print "ok $test\n"; $ok; } sub assert_output { my $str = shift; $^W=0; my $data = join('',); #print "{{$data}}\n{{$str}}\n"; assert_ok ($str eq $data); } #Test 2 $dom = new XML::DOM::Parser; my $str = < END my $doc = $dom->parse ($str); assert_ok ($doc); @result = XML::XQL::solve ('doc/foo[1, 3 to 5, -4, -2 to -1]', $doc); $result = XML::XQL::Debug::str (\@result); #print $result; assert_output ($result); __DATA__ XML-XQL-0.68/Changes0100644000076500007650000002252507611625010014301 0ustar tjmathertjmatherChange History: 0.68 (tjmather) 1/16/2003 - Delay calling tput until delimiters are needed, and don't call if user specifies his/her own delimiters first (Ed Avis) - Don't run tput if TERM is set to empty string (Ed Avis) - Filled in MANIFEST 0.67 (tjmather) 5/11/2002 - Only use tput if TERM environment variable is set (Poul Sørensen) 0.66 (tjmather) 6/20/2001 - Removed XQL.pm file generated by h2xs that shouldn't have been there. 0.65 (tjmather) 6/20/2001 - XML::XQL is now it a separate distribution from libxml-enno again! - Removed timezone warning from XML::XQL::Date (Marc Lehmann) libxml-enno-1.05 (tjmather) 5/14/2001 - Fixed XML/XQL/Query.pod to include use XML::XQL::DOM; in Synopsis (Gene Dascher) libxml-enno-1.04 (tjmather) 3/20/2001 - Updated XQLParser/Makefile.PL to use yapp instead of yapp.pl since yapp.pl was renamed to yapp starting with Parse::Yapp 0.30. This fixed a problem where it mangled XML/XQL/Parser.pm if Parse::Yapp >= 0.30 was installed. - Replaced '>' in __DATA__ section of t/xql_big.t with '>'. libxml-enno-1.03 (enno) (not released) - Fixed $intersect$ operator. It used to throw exception when parsing the XQL expression. Something like "xql_check method not implemented". (Thanks to Tatiana ) - Fixed q// and qq// operators. Typo in RE caused them to be unrecognized by the XQL expression parser. - Fixed 'any' and 'all' modifiers. Typos in Parser.yp caused them to fail. (Thanks to James Curran ) - Fixed warning on Windows when using XML::XQL, related to tput. 0.63 part of libxml-enno-1.01 (enno) 2/17/2000 - all XML::XQL::Operator classes now 'use fields', which makes them faster and smaller (see man fields(3) and man base(3)). - the minus '-' sign is now allowed in XQL function names etc. - added the XQL+ document() method, which creates XML::DOM::Documents on the fly. The document() parameter can be a simple string (i.e. filename or URL) or a query that evaluates to a bunch of filenames. See XML::XQL for details. See also new test case: t/xql_document.t - added the following methods which were found in the XPath spec to XQL+: round, floor, ceiling, concat, starts-with, contains, substring-before, substring-after, substring (not the same as substr, the index is 1-based!), translate, string-length (similar to length, but is also a method), normalize-space, sum. Also added ends-with, which is not part of XPath. See XML::XQL(3) for details. - added XML::XQL::Query::dispose(). Call dispose on your query object to clean up circular references after you're done and avoid memory leaks. 0.62 part of libxml-enno-1.00 (enno) 2/17/2000 - XML::Checker now implements the PerlSAX Handler interface. - Fixed XML::Checker::Parser to use XML::Parser::Expat::specified_attr to determine which attributes were specified (and which were defaulted by expat.) (I was using original_string before and parsing the string myself to figure out which attributes were specified, but there was a bug in my code which would generate bogus error-159's.) (Thanks to Jim Anderson ) - External DTDs with relative file paths (and without the 'file://' prefix) are now located using SGML_SEARCH_PATH. See XML::Checker::Parser pod for details. (Thanks to Stephane Bortzmeyer ) - XML::Checker::DOM is now obsolete. I moved the functionality to XML::DOM. - The error descriptions in the XML::Checker manual page now have links to the appropriate sections and Validity Constraints in the XML spec. 0.61 (enno) 8/2/1999 - Added -H option to xql.pl, which is similar to -h, but it doesn't print a file header when there are no query results for that file. - Fixed memory leak in xql.pl. It wasn't calling dispose on the XML::DOM document after it was done processing it, causing it to run out of memory when processing a lot of files. - Fixed the regular expressions for XML tokens to include Unicode values > 127 0.60 (enno) 3/19/1999 - Fixed $lt$ and $ilt$ (operator '<' was working fine) (Thanks again, Ingo) - Implemented ';;' (precedes) and ';' (immediately precedes) operators. - Added test cases t/precedes.t and t/immediately_precedes.t - Updated docs. - Fixed dependancies in Makefile.PL. Date::Manip 5.20 (or less) won't work and XML::DOM 1.11 won't work. Since I was using Date::Manip 5.33, I now require you to do the same. If you don't want to switch, you're free to change the version number in Makefile.PL, but I wouldn't recommend it. (Thanks to Andrew McNaughton ) - Reimplemented code that sorts nodes in document order. - Fixed bugs in subscript and filter operators (the ones with square brackets) - Added testcases t/subscript2.t and t/index2.t - In the subscript2 and index2 testcases only the first node was returned (Thanks to Christophe Guillon ) - Fixed all MacOS related build problems. (Those pesky newlines...) (Thanks to Arved Sandstrom for helping to fix them.) 0.59 (enno) 2/15/1999 - Performance improvement: - Removed automatic inclusion of XML::XQL::Date. Users must now explicitly 'use XML::XQL::Date;' if they want to use date() or Date objects. - Performance analysis showed that about 75% was spent building the DOM (with DOM 1.14), so let's optimize the DOM further first... - Fixed typos and grammar in the XML::XQL POD and Tutorial. (Thanks to John Durand ) - Fixed the collection functions: comment(), element() etc. They would throw exceptions like "Can't call method "_nodesByType" on an undefined value..." (Thanks to Ingo Macherius ) - Added t/comment.t test case. - Made most XQL functions process the entire list of input nodes, rather than just the first one. This allows queries like "//comment()". - Fixed bug in 'sort in document order' (sortBySrcNode) This was used by $union$ and now also by collection functions. - Fixed attribute() function. It ignored the optional parameter. 0.58 (enno) 1/25/1999 - Fixed bug in text() for Element nodes. It would sometimes omit the contents of certain text nodes when merging text within an Element node. (Thanks to Marcin Jagodzinski ) - text(0) and rawText(0) for Element nodes would include child Element nodes (contrary to the POD documentation) - Added t/text.t test case. 0.57 (enno) 1/22/1999 - Fixed code related to sorting in document order when the node list contains Attribute nodes. (Thanks to Martin Virtel ) 0.56 (enno) 1/20/1999 - Fixed Subscript related code (e.g. for queries a la "//author[2]") and added testcase t/subscript.t It used to throw the following exception: "Can't call method "setParent" without a package or object reference..." (Thanks to Arved Sandstrom ) 0.55 (enno) 1/13/1999 - Added XML::DOM to dependancy list in Makefile.PL 0.54 (enno) 1/7/1999 - XQL keywords are now case-insensitive and dollar delimiters may be omitted. - Changed regexp "s/^(\s*|#.*)*//" to "s/^(\s|#.*)*//" to avoid error "regexp *+ operand can be empty" with Perl 5.004_4 - Removed build warnings a la 'Ambiguous use of ...' with Perl 5.004_4 (Thanks to Tony Hammond ) 0.53 (enno) 12/21/1998 - Fixed Union operator (bug in sorting code) - Fixed XQL+ operators - Changed Element::xql_text and Element::xql_rawText (i.e. text() and rawText() methods) to recurse by default. - Added defineElementValueConvertor() and defineAttrValueConvertor() to support user defined conversion of Element and Attribute value() results. - Added samples/xql.pl. A nifty utility that performs XQL queries on files and formats the output in multiple ways, or modifies XML files in place. (Run xql.pl without parameters for Usage description.) - Wrote Tutorial (use man XML::XQL::Tutorial) - Added DOM_nodeType() method - Changed default nodeType() from -1 to 0. This is returned for primitives. - nodeType returns same as DOM_nodeType for all node types other than CDATASection and EntityReference. It used to return -1 for node types not specified in the XQL spec. - Fixed nodeTypeString() for processing instructions from "pi" to "processing_instruction" (as per the XQL spec) - Fixed prefix(). It used to return the entire nodeName if there was no prefix. - Changed t/sin2.t test case, so it won't spit out warnings - Simplified build environment 0.52 (enno) 12/10/1998 - Fixed Makefiles and put submodules in subdirectories. (I had some soft links in my development environment, so everything worked for me. I forgot to test the installation from scratch. Sorry...) - Added XML::DOM::Element::xql_rawTextBlocks for use in subst, map etc. - Changed subst() to work on 'text blocks' for Element nodes by default. Added MODE parameter. MODE=1 uses value() for Elements, just like version 0.51 - subst() uses xql_setValue to modify objects that match. It used to create a new object when it matched an XQL primitive (to prevent people from modifying constants in the XQL query expression), but on second thought it doesn't seem likely that that will be a problem. (Hell, it might be a feature :-) - Fixed generateFunction for when ARGCOUNT = [N, -1] - Added new() function - Cleaned up Date class and modified date() function accordingly - Added defineExpandedTypes() - Added more stuff to the POD documentation. 0.51 (enno) 12/7/1998 - First alpha release. Announced to Perl-XML mailing list. XML-XQL-0.68/lib/0040755000076500007650000000000007611625246013564 5ustar tjmathertjmatherXML-XQL-0.68/lib/XML/0040755000076500007650000000000007611625246014224 5ustar tjmathertjmatherXML-XQL-0.68/lib/XML/XQL/0040755000076500007650000000000007611625246014670 5ustar tjmathertjmatherXML-XQL-0.68/lib/XML/XQL/Query.pod0100644000076500007650000001165007314122770016473 0ustar tjmathertjmather=head1 NAME XML::XQL::Query - Creates an XQL query evaluater from a XQL expression =head1 SYNOPSIS use XML::XQL; use XML::XQL::DOM; $parser = new XML::DOM::Parser; $doc = $parser->parsefile ("file.xml"); # Return all elements with tagName='title' under the root element 'book' $query = new XML::XQL::Query (Expr => "book/title"); @result = $query->solve ($doc); # Or (to save some typing) @result = XML::XQL::solve ("book/title", $doc); =head1 DESCRIPTION To perform XQL queries on an XML::DOM document (or, in the future, on other XML storage structures), you first have to create an XML::XQL::Query object and pass it a valid XQL query expression. You can then perform queries on one or more documents by calling the solve() method. =head1 XML::XQL::Query constructor Usage, e.g: $query = new XML::XQL::Query( Expr => "book/author", Func => [ myfunc => \&my_func, # define 2 functions myfunc2 => \&my_func2 ], FuncArgCount => [ myfunc2 => [2, -1] ], # myfunc2 has 2 or more args AllowedOutSideSubquery => [ myfunc => 1 ], ConstFunc => [ myfunc2 => 1], CompareOper => [ mycmp => \&mycmp ], # define comparison operator q => "str"); # use str// as string delim =over 4 =item Expr => STRING The query expression to be evaluated. =item NodeQuery => BOOLEAN If set to 1, the query is a I as opposed to a I (which is the default.) A node query is a query that is only capable of returning Nodes. A full query is capable of returning Node values and non-Node values. Non-Node values include XML Primitives, element type names, namespace URI's, concatenated text nodes, and node type names. The distinction is significant because node queries may appear as XSL match and select patterns, while full queries have use in other applications. The difference between the two forms of queries is trivial and exists only as constraints on the syntax of node queries. Node queries may contain nested full queries. =item Func => [ FUNCNAME => FUNCREF, ...] Defines one or more functions. FUNCNAME is the name as used in the query expression. FUNCREF can be either a function reference like \&my_func or an anonymous sub. See also: defineFunction =item Method => [ FUNCNAME => FUNCREF, ...] Defines one or more methods. FUNCNAME is the name as used in the query expression. FUNCREF can be either a function reference like \&my_func or an anonymous sub. See also: defineMethod =item FuncArgCount => [ FUNCNAME => ARGCOUNT, ...] Defines the number of arguments for one or more functions or methods. FUNCNAME is the name as used in the query expression. See also: defineFunction and defineMethod =item AllowedOutsideSubquery => [ FUNCNAME => BOOLEAN, ...] Defines whether the specified function or method is allowed outside subqueries. FUNCNAME is the name as used in the query expression. See also: defineFunction and defineMethod =item ConstFunc => [ FUNCNAME => BOOLEAN, ...] Defines whether the function (not method!) is a "constant" function. FUNCNAME is the name as used in the query expression. See L for a definition of "constant" See also: defineFunction and defineMethod =item CompareOper => [ OPERNAME => FUNCREF, ...] Defines the comparison operator with the specified OPERNAME, e.g. if OPERNAME is "contains", you can use "$contains$" in the query. See also: defineComparisonOperators =item q => TOKEN Defines the q// token. See also: defineTokenQ =item qq => TOKEN Defines the qq// token. See also: defineTokenQQ =item Error => FUNCREF Defines the function that is called when errors occur during parsing the query expression. The default function prints an error message to STDERR. =item Debug => FLAGS Sets the debug level for the Yapp parser that parses the query expression. Default value is 0 (don't print anything). The maximum value is 0x17, which prints a lot of stuff. See the Parse::Yapp manpage for the meaning of the individual bits. =item Reserved hash keys Users may add their own (key, value) pairs to the Query constructor. Beware that the key 'Tree' is used internally. =back =head1 XML::XQL::Query methods =over 4 =item solve (INPUT_LIST...) Note that solve takes a list of nodes which are assumed to be in document order and must belong to the same document. E.g: $query = new XML::XQL::Query (Expr => "doc//book"); @result = $query->solve ($doc); @result2 = $query->solve ($node1, $node2, $node3); =back The following functions are also available at the query level, i.e. when called on a Query object they only affect this Query and no others: defineFunction, defineMethod, defineComparisonOperators, defineTokenQ, defineTokenQQ See L for details. Another way to define these features for a particular Query is by passing the appropriate values to the XML::XQL::Query constructor. =head1 SEE ALSO L for general information about the XML::XQL module L which describes the XQL syntax XML-XQL-0.68/lib/XML/XQL/DOM.pm0100644000076500007650000002617307314122770015645 0ustar tjmathertjmather############################################################################ # Copyright (c) 1998 Enno Derksen # All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. ############################################################################ # # Functions added to the XML::DOM implementation for XQL support # # NOTE: This code is a bad example of how to use XML::DOM. # I'm accessing internal (private) data members for a little gain in performance. # When the internal DOM implementation changes, this code will no longer work. # But since I maintain XML::DOM, it's easy for me to keep them in sync. # Regular users are adviced to use the XML::DOM API as described in the # documentation. # use strict; package XML::XQL::DOM; BEGIN { require XML::DOM; # import constant field definitions, e.g. _Doc import XML::DOM::Node qw{ :Fields }; } package XML::DOM::Node; sub xql { my $self = shift; # Odd number of args, assume first is XQL expression without 'Expr' key unshift @_, 'Expr' if (@_ % 2 == 1); my $query = new XML::XQL::Query (@_); my @result = $query->solve ($self); $query->dispose; @result; } sub xql_sortKey { my $key = $_[0]->[_SortKey]; return $key if defined $key; $key = XML::XQL::createSortKey ($_[0]->[_Parent]->xql_sortKey, $_[0]->xql_childIndex, 1); #print "xql_sortKey $_[0] ind=" . $_[0]->xql_childIndex . " key=$key str=" . XML::XQL::keyStr($key) . "\n"; $_[0]->[_SortKey] = $key; } # Find previous sibling that is not a text node with ignorable whitespace sub xql_prevNonWS { my $self = shift; my $parent = $self->[_Parent]; return unless $parent; for (my $i = $parent->getChildIndex ($self) - 1; $i >= 0; $i--) { my $node = $parent->getChildAtIndex ($i); return $node unless $node->xql_isIgnorableWS; # skip whitespace } undef; } # True if it's a Text node with just whitespace and xml::space != "preserve" sub xql_isIgnorableWS { 0; } # Whether the node should preserve whitespace # It should if it has attribute xml:space="preserve" sub xql_preserveSpace { $_[0]->[_Parent]->xql_preserveSpace; } sub xql_element { #?? I wonder which implemention is used for e.g. DOM::Text, since XML::XQL::Node also has an implementation []; } sub xql_document { $_[0]->[_Doc]; } sub xql_node { my $kids = $_[0]->[_C]; if (defined $kids) { # Must copy the list or else we return a blessed reference # (which causes trouble later on) my @list = @$kids; return \@list; } []; } #?? implement something to support NamedNodeMaps in DocumentType sub xql_childIndex { $_[0]->[_Parent]->getChildIndex ($_[0]); } #?? implement something to support NamedNodeMaps in DocumentType sub xql_childCount { my $ch = $_[0]->[_C]; defined $ch ? scalar(@$ch) : 0; } sub xql_parent { $_[0]->[_Parent]; } sub xql_DOM_nodeType { $_[0]->getNodeType; } sub xql_nodeType { $_[0]->getNodeType; } # As it appears in the XML document sub xql_xmlString { $_[0]->toString; } package XML::DOM::Element; sub xql_attribute { my ($node, $attrName) = @_; if (defined $attrName) { my $attr = $node->getAttributeNode ($attrName); defined ($attr) ? [ $attr ] : []; } else { defined $node->[_A] ? $node->[_A]->getValues : []; } } # Used by XML::XQL::Union::genSortKey to generate sort keys # Returns the maximum of the number of children and the number of Attr nodes. sub xql_childCount { my $n = scalar @{$_[0]->[_C]}; my $m = defined $_[0]->[_A] ? $_[0]->[_A]->getLength : 0; return $n > $m ? $n : $m; } sub xql_element { my ($node, $elem) = @_; my @list; if (defined $elem) { for my $kid (@{$node->[_C]}) { push @list, $kid if $kid->isElementNode && $kid->[_TagName] eq $elem; } } else { for my $kid (@{$node->[_C]}) { push @list, $kid if $kid->isElementNode; } } \@list; } sub xql_nodeName { $_[0]->[_TagName]; } sub xql_baseName { my $name = $_[0]->[_TagName]; $name =~ s/^\w*://; $name; } sub xql_prefix { my $name = $_[0]->[_TagName]; $name =~ /([^:]+):/; $1; } sub xql_rawText { my ($self, $recurse) = @_; $recurse = 1 unless defined $recurse; my $text = ""; for my $kid (@{$self->xql_node}) { my $type = $kid->xql_nodeType; # type=1: element # type=3: text (Text, CDATASection, EntityReference) if (($type == 1 && $recurse) || $type == 3) { $text .= $kid->xql_rawText ($recurse); } } $text; } sub xql_text { my ($self, $recurse) = @_; $recurse = 1 unless defined $recurse; my $j = -1; my @text; my $last_was_text = 0; # Collect text blocks. Consecutive blocks of Text, CDataSection and # EntityReference nodes should be merged without stripping and without # putting spaces in between. for my $kid (@{$self->xql_node}) { my $type = $kid->xql_nodeType; if ($type == 1) # 1: element { if ($recurse) { $text[++$j] = $kid->xql_text ($recurse); } $last_was_text = 0; } elsif ($type == 3) # 3: text (Text, CDATASection, EntityReference) { ++$j unless $last_was_text; # next text block $text[$j] .= $kid->getData; $last_was_text = 1; } else # e.g. Comment { $last_was_text = 0; } } # trim whitespace and remove empty blocks my $i = 0; my $n = @text; while ($i < $n) { # similar to XML::XQL::trimSpace $text[$i] =~ s/^\s+//; $text[$i] =~ s/\s+$//; if ($text[$i] eq "") { splice (@text, $i, 1); # remove empty block $n--; } else { $i++; } } join (" ", @text); } # # Returns a list of text blocks for this Element. # A text block is a concatenation of consecutive text-containing nodes (i.e. # Text, CDATASection or EntityReference nodes.) # For each text block a reference to an array is returned with the following # 3 items: # [0] index of first node of the text block # [1] index of last node of the text block # [2] concatenation of the raw text (of the nodes in this text block) # # The text blocks are returned in reverse order for the convenience of # the routines that want to modify the text blocks. # sub xql_rawTextBlocks { my ($self) = @_; my @result; my $curr; my $prevWasText = 0; my $kids = $self->[_C]; my $n = @$kids; for (my $i = 0; $i < $n; $i++) { my $node = $kids->[$i]; # 3: text (Text, CDATASection, EntityReference) if ($node->xql_nodeType == 3) { if ($prevWasText) { $curr->[1] = $i; $curr->[2] .= $node->getData; } else { $curr = [$i, $i, $node->getData]; unshift @result, $curr; $prevWasText = 1; } } else { $prevWasText = 0; } } @result; } sub xql_replaceBlockWithText { my ($self, $start, $end, $text) = @_; for (my $i = $end; $i > $start; $i--) { # dispose of the old nodes $self->removeChild ($self->[_C]->[$i])->dispose; } my $node = $self->[_C]->[$start]; my $newNode = $self->[_Doc]->createTextNode ($text); $self->replaceChild ($newNode, $node)->dispose; } sub xql_setValue { my ($self, $str) = @_; # Remove all children for my $kid (@{$self->[_C]}) { $self->removeChild ($kid); } # Add a (single) text node $self->appendChild ($self->[_Doc]->createTextNode ($str)); } sub xql_value { XML::XQL::elementValue ($_[0]); } sub xql_preserveSpace { # attribute value should be "preserve" (1), "default" (0) or "" (ask parent) my $space = $_[0]->getAttribute ("xml:space"); $space eq "" ? $_[0]->[_Parent]->xql_preserveSpace : ($space eq "preserve"); } package XML::DOM::Attr; sub xql_sortKey { my $key = $_[0]->[_SortKey]; return $key if defined $key; $_[0]->[_SortKey] = XML::XQL::createSortKey ($_[0]->xql_parent->xql_sortKey, $_[0]->xql_childIndex, 0); } sub xql_nodeName { $_[0]->getNodeName; } sub xql_text { XML::XQL::trimSpace ($_[0]->getValue); } sub xql_rawText { $_[0]->getValue; } sub xql_value { XML::XQL::attrValue ($_[0]); } sub xql_setValue { $_[0]->setValue ($_[1]); } sub xql_baseName { my $name = $_[0]->getNodeName; $name =~ s/^\w*://; $name; } sub xql_prefix { my $name = $_[0]->getNodeName; $name =~ s/:\w*$//; $name; } sub xql_parent { $_[0]->[_UsedIn]->{''}->{Parent}; } sub xql_childIndex { my $map = $_[0]->[_UsedIn]; $map ? $map->getChildIndex ($_[0]) : 0; } package XML::DOM::Text; sub xql_rawText { $_[0]->[_Data]; } sub xql_text { XML::XQL::trimSpace ($_[0]->[_Data]); } sub xql_setValue { $_[0]->setData ($_[1]); } sub xql_isIgnorableWS { $_[0]->[_Data] =~ /^\s*$/ && !$_[0]->xql_preserveSpace; } package XML::DOM::CDATASection; sub xql_rawText { $_[0]->[_Data]; } sub xql_text { XML::XQL::trimSpace ($_[0]->[_Data]); } sub xql_setValue { $_[0]->setData ($_[1]); } sub xql_nodeType { 3; # it contains text, so XQL spec states it's a text node } package XML::DOM::EntityReference; BEGIN { # import constant field definitions, e.g. _Data import XML::DOM::CharacterData qw{ :Fields }; } sub xql_text { $_[0]->getData; } sub xql_rawText { XML::XQL::trimSpace ($_[0]->[_Data]); } sub xql_setValue { $_[0]->setData ($_[1]); } sub xql_nodeType { 3; # it contains text, so XQL spec states it's a text node } package XML::DOM::Document; BEGIN { # import constant field definitions, e.g. _TagName import XML::DOM::Element qw{ :Fields }; } sub xql_sortKey { ""; } sub xql_element { my ($node, $elem) = @_; my @list; if (defined $elem) { for my $kid (@{$node->[_C]}) { push @list, $kid if $kid->isElementNode && $kid->[_TagName] eq $elem; } } else { for my $kid (@{$node->[_C]}) { push @list, $kid if $kid->isElementNode; } } \@list; } sub xql_parent { undef; } # By default the elements in a document don't preserve whitespace sub xql_preserveSpace { 0; } package XML::DOM::DocumentFragment; BEGIN { # import constant field definitions, e.g. _TagName import XML::DOM::Element qw{ :Fields }; } sub xql_element { my ($node, $elemName) = @_; my @list; if (defined $elemName) { for my $kid (@{$node->[_C]}) { push @list, $kid if $kid->isElementNode && $kid->[_TagName] eq $elemName; } } else { for my $kid (@{$node->[_C]}) { push @list, $kid if $kid->isElementNode; } } \@list; } sub xql_parent { undef; } 1; # module loaded successfuly __END__ =head1 NAME XML::XQL::DOM - Adds XQL support to XML::DOM nodes =head1 SYNOPSIS use XML::XQL; use XML::XQL::DOM; $parser = new XML::DOM::Parser; $doc = $parser->parsefile ("file.xml"); # Return all elements with tagName='title' under the root element 'book' $query = new XML::XQL::Query (Expr => "book/title"); @result = $query->solve ($doc); # Or (to save some typing) @result = XML::XQL::solve ("book/title", $doc); # Or (see XML::DOM::Node) @result = $doc->xql ("book/title"); =head1 DESCRIPTION XML::XQL::DOM adds methods to L nodes to support XQL queries on XML::DOM document structures. See L and L for more details. L describes the B method. XML-XQL-0.68/lib/XML/XQL/Date.pm0100644000076500007650000001172607314123760016101 0ustar tjmathertjmather############################################################################ # Copyright (c) 1998 Enno Derksen # All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. ############################################################################ package XML::XQL::Date; use vars qw(@ISA); @ISA = qw( XML::XQL::PrimitiveType ); use strict; use Carp; #BEGIN #{ # # Date::Manip relies on setting of $TZ. # unless (defined $ENV{TZ}) # { # $ENV{TZ} = "EST5EDT"; # warn "XML::XQL::Date - setting timezone \$ENV{TZ} to EST5EDT (east coast USA.) Set your TZ environment variable to avoid this message."; # } #} use Date::Manip; BEGIN { # add date() implementation to XQL engine. XML::XQL::defineFunction ("date", \&XML::XQL::Date::date, 1, 1, 1); }; use overload 'fallback' => 1, # use default operators, if not specified '<=>' => \&compare, # also takes care of <, <=, ==, != etc. 'cmp' => \&compare, # also takes care of le, lt, eq, ne, etc. '""' => \&yyyymmddhhmmss; # conversion to string uses yyyymmddhhmmss sub new { my $class = shift; my (%args); if (@_ < 2) { my $str = @_ ? $_[0] : ""; %args = (String => $str); } else { %args = @_; } my $self = bless \%args, $class; if (@_ < 2) { my $date = $self->createInternal (@_ ? $_[0] : "now"); $date = "" unless isValidDate ($date); $self->{Internal} = $date; } $self; } sub createInternal { my ($self, $str) = @_; Date::Manip::ParseDate ($str); # From Date::Manip: # # 2 digit years fall into the 100 year period given by [ CURR-N, # CURR+(99-N) ] where N is 0-99. Default behavior is 89, but other useful # numbers might be 0 (forced to be this year or later) and 99 (forced to be # this year or earlier). It can also be set to "c" (current century) or # "cNN" (i.e. c18 forces the year to bet 1800-1899). Also accepts the # form cNNNN to give the 100 year period NNNN to NNNN+99. #$Date::Manip::YYtoYYYY=89; # Use this to force the current date to be set to this: #$Date::Manip::ForceDate=""; } sub isValidDate # static method { my ($date) = @_; return 0 unless defined $date; my $year = substr ($date, 0, 4) || 0; $year > 1500; #?? arbitrary limit - years < 100 cause problems in Date::Manip } sub ymdhms { my $self = shift; if (@_) { my ($y, $mon, $d, $h, $m, $s) = @; #?? implement } else { #?? test: x skips a character. Format: "YYYYMMDDhh:mm::ss" return () unless length $self->{Internal}; # print "ymhds " . $self->{Internal} . "\n"; unpack ("A4A2A2A2xA2xA2", $self->{Internal}); } } sub yyyymmddhhmmss { my ($self) = @_; my ($y, $mon, $d, $h, $m, $s) = $self->ymdhms; $y ? "$y-$mon-${d}T$h:$m:$s" : ""; # using Date::Manip::UnixDate is a bit too slow for my liking #?? could add support for other formats } sub xql_toString { #?? use $_[0]->{String} or $_[0]->yyyymmddhhmmss; } sub xql_compare { my ($self, $other) = @_; my $type = ref ($self); if (ref ($other) ne $type) { my $str = $other->xql_toString; # Allow users to plug in their own Date class $other = eval "new $type (\$str)"; #?? check result? } #print "date::compare self=" . $self->{Internal} . " other=" . $other->{Internal}. "\n"; $self->{Internal} cmp $other->{Internal}; } sub xql_setSourceNode { $_[0]->{SourceNode} = $_[1]; } sub xql_sourceNode { $_[0]->{SourceNode}; } sub xql_setValue { my ($self, $val) = @_; $self->{Internal} = $self->createInternal ($val); $self->{String} = $val; } # The XQL date() function sub date # static method { my ($context, $listref, $text) = @_; $text = XML::XQL::toList ($text->solve ($context, $listref)); my @result = (); for my $val (@$text) { # Using xql_new allows users to plug-in their own Date class my $date = XML::XQL::xql_new ("date", $val->xql_toString); # print "date $val " . XML::XQL::d($val) . " " . $date->xql_toString . "\n"; push @result, $date; } \@result; } 1; # module return code __END__ =head1 NAME XML::XQL::Date - Adds an XQL::Node type for representing and comparing dates and times =head1 SYNOPSIS use XML::XQL; use XML::XQL::Date; my $query = new XML::XQL::Query (Expr => "doc//timestamp[. < date('12/31/1999')]"); my @results = $query->solve ($doc); =head1 DESCRIPTION This package uses the L package to add an XQL node type (called XML::XQL::Date) that can be used to represent dates and times. The Date::Manip package can parse almost any date or time format imaginable. (I tested it with Date::Manip 5.33 and I know for sure that it doesn't work with 5.20 or lower.) It also adds the XQL B function which creates an XML::XQL::Date object from a string. See L for a description of the date() function. You can plug in your own Date type, if you don't want to use Date::Manip for some reason. See L and the XML::XQL::Date source file for more details. XML-XQL-0.68/lib/XML/XQL/Tutorial.pod0100644000076500007650000011642007314122770017172 0ustar tjmathertjmather=head1 NAME XML::XQL::Tutorial - Describes the XQL query syntax =head1 DESCRIPTION This document describes basic the features of the XML Query Language (XQL.) A proposal for the XML Query Language (XQL) specification was submitted to the XSL Working Group in September 1998. The spec can be found at L. Since it is only a proposal at this point, things may change, but it is very likely that the final version will be close to the proposal. Most of this document was copied straight from the spec. See also the L man page. =head1 INTRODUCTION XQL (XML Query Language) provides a natural extension to the XSL pattern language. It builds upon the capabilities XSL provides for identifying classes of nodes, by adding Boolean logic, filters, indexing into collections of nodes, and more. XQL is designed specifically for XML documents. It is a general purpose query language, providing a single syntax that can be used for queries, addressing, and patterns. XQL is concise, simple, and powerful. XQL is designed to be used in many contexts. Although it is a superset of XSL patterns, it is also applicable to providing links to nodes, for searching repositories, and for many other applications. Note that the term XQL is a working term for the language described in this proposal. It is not their intent that this term be used permanently. Also, beware that another query language exists called XML-QL, which uses a syntax very similar to SQL. The L module has added functionality to the XQL spec, called I. To allow only XQL functionality as described in the spec, use the XML::XQL::Strict module. Note that the XQL spec makes the distinction between core XQL and XQL extensions. This implementation makes no distinction and the Strict module, therefore, implements everything described in the XQL spec. See the L man page for more information about the Strict module. This tutorial will clearly indicate when referring to XQL+. =head1 XQL Patterns This section describes the core XQL notation. These features should be part of every XQL implementation, and serve as the base level of functionality for its use in different technologies. The basic syntax for XQL mimics the URI directory navigation syntax, but instead of specifying navigation through a physical file structure, the navigation is through elements in the XML tree. For example, the following URI means find the foo.jpg file within the bar directory: bar/foo.jpg Similarly, in XQL, the following means find the collection of fuz elements within baz elements: baz/fuz Throughout this document you will find numerous samples. They refer to the data shown in the sample file at the end of this man page. =head1 Context A I is the set of nodes against which a query operates. For the entire query, which is passed to the L constructor through the I option, the context is the list of input nodes that is passed to the query() method. XQL allows a query to select between using the current context as the input context and using the 'root context' as the input context. The 'root context' is a context containing only the root-most element of the document. When using XML::DOM, this is the Document object. By default, a query uses the current context. A query prefixed with '/' (forward slash) uses the root context. A query may optionally explicitly state that it is using the current context by using the './' (dot, forward slash) prefix. Both of these notations are analogous to the notations used to navigate directories in a file system. The './' prefix is only required in one situation. A query may use the '//' operator to indicate recursive descent. When this operator appears at the beginning of the query, the initial '/' causes the recursive decent to perform relative to the root of the document or repository. The prefix './/' allows a query to perform a recursive descent relative to the current context. =over 4 =item Examples: Find all author elements within the current context. Since the period is really not used alone, this example forward-references other features: ./author Note that this is equivalent to: author Find the root element (bookstore) of this document: /bookstore Find all author elements anywhere within the current document: //author Find all books where the value of the style attribute on the book is equal to the value of the specialty attribute of the bookstore element at the root of the document: book[/bookstore/@specialty = @style] =back =head1 Query Results The collection returned by an XQL expression preserves document order, hierarchy, and identity, to the extent that these are defined. That is, a collection of elements will always be returned in document order without repeats. Note that the spec states that the order of attributes within an element is undefined, but that this implementation does keep attributes in document order. See the L man page for more details regarding I. =head1 Collections - 'element' and '.' The collection of all elements with a certain tag name is expressed using the tag name itself. This can be qualified by showing that the elements are selected from the current context './', but the current context is assumed and often need not be noted explicitly. =over 4 =item Examples: Find all first-name elements. These examples are equivalent: ./first-name first-name Find all unqualified book elements: book Find all first.name elements: first.name =back =head1 Selecting children and descendants - '/' and '//' The collection of elements of a certain type can be determined using the path operators ('/' or '//'). These operators take as their arguments a collection (left side) from which to query elements, and a collection indicating which elements to select (right side). The child operator ('/')selects from immediate children of the left-side collection, while the descendant operator ('//') selects from arbitrary descendants of the left-side collection. In effect, the '//' can be thought of as a substitute for one or more levels of hierarchy. Note that the path operators change the context as the query is performed. By stringing them together users can 'drill down' into the document. =over 4 =item Examples: Find all first-name elements within an author element. Note that the author children of the current context are found, and then first-name children are found relative to the context of the author elements: author/first-name Find all title elements, one or more levels deep in the bookstore (arbitrary descendants): bookstore//title Note that this is different from the following query, which finds all title elements that are grandchildren of bookstore elements: bookstore/*/title Find emph elements anywhere inside book excerpts, anywhere inside the bookstore: bookstore//book/excerpt//emph Find all titles, one or more levels deep in the current context. Note that this situation is essentially the only one where the period notation is required: .//title =back =head1 Collecting element children - '*' An element can be referenced without using its name by substituting the '*' collection. The '*' collection returns all elements that are children of the current context, regardless of their tag name. =over 4 =item Examples: Find all element children of author elements: author/* Find all last-names that are grand-children of books: book/*/last-name Find the grandchildren elements of the current context: */* Find all elements with specialty attributes. Note that this example uses subqueries, which are covered in Filters, and attributes, which are discussed in Finding an attribute: *[@specialty] =back =head1 Finding an attribute - '@' Attribute names are preceded by the '@' symbol. XQL is designed to treat attributes and sub-elements impartially, and capabilities are equivalent between the two types wherever possible. Note: attributes cannot contain subelements. Thus, attributes cannot have path operators applied to them in a query. Such expressions will result in a syntax error. The XQL spec states that attributes are inherently unordered and indices cannot be applied to them, but this implementation allows it. =over 4 =item Examples: Find the style attribute of the current element context: @style Find the exchange attribute on price elements within the current context: price/@exchange The following example is not valid: price/@exchange/total Find all books with style attributes. Note that this example uses subqueries, which are covered in Filters: book[@style] Find the style attribute for all book elements: book/@style =back =head1 XQL Literals XQL query expressions may contain literal values (i.e. constants.) Numbers (integers and floats) are wrapped in XML::XQL::Number objects and strings in XML::XQL::Text objects. Booleans (as returned by true() and false()) are wrapped in XML::XQL::Boolean objects. Strings must be enclosed in single or double quotes. Since XQL does not allow escaping of special characters, it's impossible to create a string with both a single and a double quote in it. To remedy this, XQL+ has added the q// and qq// string delimiters which behave just like they do in Perl. For Numbers, exponential notation is not allowed. Use the XQL+ function eval() to circumvent this problem. See L man page for details. The empty list or undef is represented by [] (i.e. reference to empty array) in this implementation. =over 4 =item Example Integer Numbers: 234 -456 Floating point Numbers: 1.23 -0.99 Strings: "some text with 'single' quotes" 'text with "double" quotes' Not allowed: 1.23E-4 (use eval("1.23E-4", "Number") in XQL+) "can't use \"double \"quotes" (use q/can't use "double" quotes/ in XQL+) =back =head1 Grouping - '()' Parentheses can be used to group collection operators for clarity or where the normal precedence is inadequate to express an operation. =head1 Filters - '[]' Constraints and branching can be applied to any collection by adding a filter clause '[ ]' to the collection. The filter is analogous to the SQL WHERE clause with ANY semantics. The filter contains a query within it, called the subquery. The subquery evaluates to a Boolean, and is tested for each element in the collection. Any elements in the collection failing the subquery test are omitted from the result collection. For convenience, if a collection is placed within the filter, a Boolean TRUE is generated if the collection contains any members, and a FALSE is generated if the collection is empty. In essence, an expression such as author/degree implies a collection-to-Boolean conversion function like the following mythical 'there-exists-a' method. author[.there-exists-a(degree)] Note that any number of filters can appear at a given level of an expression. Empty filters are not allowed. =over 4 =item Examples: Find all books that contain at least one excerpt element: book[excerpt] Find all titles of books that contain at least one excerpt element: book[excerpt]/title Find all authors of books where the book contains at least one excerpt, and the author has at least one degree: book[excerpt]/author[degree] Find all books that have authors with at least one degree: book[author/degree] Find all books that have an excerpt and a title: book[excerpt][title] =back =head2 Any and all semantics - '$any$' and '$all$' Users can explicitly indicate whether to use any or all semantics through the $any$ and $all$ keywords. $any$ flags that a condition will hold true if any item in a set meets that condition. $all$ means that all elements in a set must meet the condition for the condition to hold true. $any$ and $all$ are keywords that appear before a subquery expression within a filter. =over 4 =item Examples: Find all author elements where one of the last names is Bob: author[last-name = 'Bob'] author[$any$ last-name = 'Bob'] Find all author elements where none of the last-name elements are Bob: author[$all$ last-name != 'Bob'] Find all author elements where the first last name is Bob: author[last-name[0] = 'Bob'] =back =head1 Indexing into a collection - '[]' and '$to$' XQL makes it easy to find a specific node within a set of nodes. Simply enclose the index ordinal within square brackets. The ordinal is 0 based. A range of elements can be returned. To do so, specify an expression rather than a single value inside of the subscript operator (square brackets). Such expressions can be a comma separated list of any of the following: n Returns the nth element -n Returns the element that is n-1 units from the last element. E.g., -1 means the last element. -2 is the next to last element. m $to$ n Returns elements m through n, inclusive =over 4 =item Examples: Find the first author element: author[0] Find the third author element that has a first-name: author[first-name][2] Note that indices are relative to the parent. In other words, consider the following data: The following expression will return the first y from each of the x's: x/y[0] The following will return the first y from the entire set of y's within x's: (x/y)[0] The following will return the first y from the first x: x[0]/y[0] Find the first and fourth author elements: author[0,3] Find the first through fourth author elements: author[0 $to$ 3] Find the first, the third through fifth, and the last author elements: author[0, 2 $to$ 4, -1] Find the last author element: author[-1] =back =head1 Boolean Expressions Boolean expressions can be used within subqueries. For example, one could use Boolean expressions to find all nodes of a particular value, or all nodes with nodes in particular ranges. Boolean expressions are of the form ${op}$, where {op} may be any expression of the form {b|a} - that is, the operator takes lvalue and rvalue arguments and returns a Boolean result. Note that the XQL Extensions section defines additional Boolean operations. =head2 Boolean AND and OR - '$and$' and '$or$' $and$ and $or$ are used to perform Boolean ands and ors. The Boolean operators, in conjunction with grouping parentheses, can be used to build very sophisticated logical expressions. Note that spaces are not significant and can be omitted, or included for clarity as shown here. =over 4 =item Examples: Find all author elements that contain at least one degree and one award. author[degree $and$ award] Find all author elements that contain at least one degree or award and at least one publication. author[(degree $or$ award) $and$ publication] =back =head2 Boolean NOT - '$not$' $not$ is a Boolean operator that negates the value of an expression within a subquery. =over 4 =item Examples: Find all author elements that contain at least one degree element and that contain no publication elements. author[degree $and$ $not$ publication] Find all author elements that contain publications elements but do not contain either degree elements or award elements. author[$not$ (degree $or$ award) $and$ publication] =back =head1 Union and intersection - '$union$', '|' and '$intersect$' The $union$ operator (shortcut is '|') returns the combined set of values from the query on the left and the query on the right. Duplicates are filtered out. The resulting list is sorted in document order. Note: because this is a union, the set returned may include 0 or more elements of each element type in the list. To restrict the returned set to nodes that contain at least one of each of the elements in the list, use a filter, as discussed in Filters. The $intersect$ operator returns the set of elements in common between two sets. =over 4 =item Examples: Find all first-names and last-names: first-name $union$ last-name Find all books and magazines from a bookstore: bookstore/(book | magazine) Find all books and all authors: book $union$ book/author Find the first-names, last-names, or degrees from authors within either books or magazines: (book $union$ magazine)/author/(first-name $union$ last-name $union$ degree) Find all books with author/first-name equal to 'Bob' and all magazines with price less than 10: book[author/first-name = 'Bob'] $union$ magazine[price $lt$ 10] =back =head1 Equivalence - '$eq$', '=', '$ne$' and '!=' The '=' sign is used for equality; '!=' for inequality. Alternatively, $eq$ and $ne$ can be used for equality and inequality. Single or double quotes can be used for string delimiters in expressions. This makes it easier to construct and pass XQL from within scripting languages. For comparing values of elements, the value() method is implied. That is, last-name < 'foo' really means last-name!value() < 'foo'. Note that filters are always with respect to a context. That is, the expression book[author] means for every book element that is found, see if it has an author subelement. Likewise, book[author = 'Bob'] means for every book element that is found, see if it has a subelement named author whose value is 'Bob'. One can examine the value of the context as well, by using the . (period). For example, book[. = 'Trenton'] means for every book that is found, see if its value is 'Trenton'. =over 4 =item Examples: Find all author elements whose last name is Bob: author[last-name = 'Bob'] author[last-name $eq$ 'Bob'] Find all authors where the from attribute is not equal to 'Harvard': degree[@from != 'Harvard'] degree[@from $ne$ 'Harvard'] Find all authors where the last-name is the same as the /guest/last-name element: author[last-name = /guest/last-name] Find all authors whose text is 'Matthew Bob': author[. = 'Matthew Bob'] author = 'Matthew Bob' =back =head2 Comparison - '<', '<=', '>', '>=', '$lt', '$ilt$' etc. A set of binary comparison operators is available for comparing numbers and strings and returning Boolean results. $lt$, $le$, $gt$, $ge$ are used for less than, less than or equal, greater than, or greater than or equal. These same operators are also available in a case insensitive form: $ieq$, $ine$, $ilt$, $ile$, $igt$, $ige$. <, <=, > and >= are allowed short cuts for $lt$, $le$, $gt$ and $ge$. =over 4 =item Examples: Find all author elements whose last name is bob and whose price is > 50 author[last-name = 'Bob' $and$ price $gt$ 50] Find all authors where the from attribute is not equal to 'Harvard': degree[@from != 'Harvard'] Find all authors whose last name begins with 'M' or greater: author[last-name $ge$ 'M'] Find all authors whose last name begins with 'M', 'm' or greater: author[last-name $ige$ 'M'] Find the first three books: book[index() $le$ 2] Find all authors who have more than 10 publications: author[publications!count() $gt$ 10] =back =head2 XQL+ Match operators - '$match$', '$no_match$', '=~' and '!~' XQL+ defines additional operators for pattern matching. The $match$ operator (shortcut is '=~') returns TRUE if the lvalue matches the pattern described by the rvalue. The $no_match$ operator (shortcut is '!~') returns FALSE if they match. Both lvalue and rvalue are first cast to strings. The rvalue string should have the syntax of a Perl rvalue, that is the delimiters should be included and modifiers are allowed. When using delimiters other than slashes '/', the 'm' should be included. The rvalue should be a string, so don't forget the quotes! (Or use the q// or qq// delimiters in XQL+, see L man page.) Note that you can't use the Perl substitution operator s/// here. Try using the XQL+ subst() function instead. =over 4 =item Examples: Find all authors whose name contains bob or Bob: author[first-name =~ '/[Bb]ob/'] Find all book titles that don't contain 'Trenton' (case-insensitive): book[title !~ 'm!trenton!i'] =back =head2 Oher XQL+ comparison operators - '$isa', '$can$' See the L man page for other operators available in XQL+. =head2 Comparisons and vectors The lvalue of a comparison can be a vector or a scalar. The rvalue of a comparison must be a scalar or a value that can be cast at runtime to a scalar. If the lvalue of a comparison is a set, then any (exists) semantics are used for the comparison operators. That is, the result of a comparison is true if any item in the set meets the condition. =head2 Comparisons and literals The spec states that the lvalue of an expression cannot be a literal. That is, I<'1' = a> is not allowed. This implementation allows it, but it's not clear how useful that is. =head2 Casting of literals during comparison Elements, attributes and other XML node types are casted to strings (Text) by applying the value() method. The value() method calls the text() method by default, but this behavior can be altered by the user, so the value() method may return other XQL data types. When two values are compared, they are first casted to the same type. See the L man page for details on casting. Note that the XQL spec is not very clear on how values should be casted for comparison. Discussions with the authors of the XQL spec revealed that there was some disagreement and their implementations differed on this point. This implementation is closest to that of Joe Lapp from webMethods, Inc. =head1 Methods - 'method()' or 'query!method()' XQL makes a distinction between functions and methods. See the L man page for details. XQL provides methods for advanced manipulation of collections. These methods provide specialized collections of nodes (see Collection methods), as well as information about sets and nodes. Methods are of the form I Consider the query book[author]. It will find all books that have authors. Formally, we call the book corresponding to a particular author the reference node for that author. That is, every author element that is examined is an author for one of the book elements. (See the Annotated XQL BNF Appendix for a much more thorough definition of reference node and other terms. See also the XML::XQL man page.) Methods always apply to the reference node. For example, the text() method returns the text contained within a node, minus any structure. (That is, it is the concatenation of all text nodes contained with an element and its descendants.) The following expression will return all authors named 'Bob': author[text() = 'Bob'] The following will return all authors containing a first-name child whose text is 'Bob': author[first-name!text() = 'Bob'] The following will return all authors containing a child named Bob: author[*!text() = 'Bob'] Method names are case sensitive. See the L man page on how to define your own methods and functions. =head2 Information methods The following methods provide information about nodes in a collection. These methods return strings or numbers, and may be used in conjunction with comparison operators within subqueries. =over 4 =item Method: text() The text() method concatenates text of the descendents of a node, normalizing white space along the way. White space will be preserved for a node if the node has the xml:space attribute set to 'preserve', or if the nearest ancestor with the xml:space attribute has the attribute set to 'preserve'. When white space is normalized, it is normalized across the entire string. Spaces are used to separate the text between nodes. When entity references are used in a document, spacing is not inserted around the entity refs when they are expanded. In this implementation, the method may receive an optional parameter to indicate whether the text() of Element nodes should include the text() of its Element descendants. See L man page for details. Examples: Find the authors whose last name is 'Bob': author[last-name!text() = 'Bob'] Note this is equivalent to: author[last-name = 'Bob'] Find the authors with value 'Matthew Bob': author[text() = 'Matthew Bob'] author[. = 'Matthew Bob'] author = 'Matthew Bob' =item Method: rawText() The rawText() method is similar to the text() method, but it does not normalize whitespace. In this implementation, the method may receive an optional parameter to indicate whether the rawText() of Element nodes should include the rawText() of its Element descendants. See L man page for details. =item Method: value() Returns a type cast version of the value of a node. If no data type is provided, returns the same as text(). =over 4 =item Shortcuts For the purposes of comparison, value( )is implied if omitted. In other words, when two items are compared, the comparison is between the value of the two items. Remember that in absence of type information, value() returns text(). The following examples are equivalent: author[last-name!value() = 'Bob' $and$ first-name!value() = 'Joe'] author[last-name = 'Bob' $and$ first-name = 'Joe'] price[@intl!value() = 'canada'] price[@intl = 'canada'] =back =item Method: nodeType() Returns a number to indicate the type of the node. The values were based on the node type values in the DOM: element 1 attribute 2 text 3 entity 6 (not in XQL spec) PI 7 comment 8 document 9 doc. fragment 10 (not in XQL spec) notation 11 (not in XQL spec) Note that in XQL, CDATASection nodes and EntityReference nodes also return 3, whereas in the DOM CDATASection returns 4 and EntityReference returns 5. Use the XQL+ method DOM_nodeType() to get DOM node type values. See the L man page for node type values of nodes not mentioned here. =item Method: nodeTypeString Returns the name of the node type in lowercase or an empty string. The following node types are currently supported 1 (element), 2 (attribute), 3 (text), 7 (processing_instruction), 8 (comment), 9 (document) =item Method: nodeName() Returns the tag name for Element nodes and the attribute name of attributes. =back =head2 Collection index methods =over 4 =item Method: index() Returns the index of the value within the search context (i.e. with the input list of the subquery.) This is not necessarily the same as the index of a node within its parent node. Note that the XQL spec doesn't explain it well. =over 4 =item Examples: Find the first 3 degrees: degree[index() $lt$ 3] Note that it skips over other nodes that may exist between the degree elements. Consider the following data: The following expression will return the first y from each x: x/y[index() = 0] This could also be accomplished by (see Indexing into a Collection): x/y[0] =back =item Method: end() The end() method returns true for the last element in the search context. Again, the XQL spec does not explain it well. =over 4 =item Examples: Find the last book: book[end()] Find the last author for each book: book/author[end()] Find the last author from the entire set of authors of books: (book/author)[end()] =back =back =head2 Aggregate methods =over 4 =item Method: count( [QUERY] ) Returns the number of values inside the search context. In XQL+, when the optional QUERY parameter is supplied, it returns the number of values returned by the QUERY. =back =head2 Namespace methods The following methods can be applied to a node to return namespace information. =over 4 =item Method: baseName() Returns the local name portion of the node, excluding the prefix. Local names are defined only for element nodes and attribute nodes. The local name of an element node is the local portion of the node's element type name. The local name of an attribute node is the local portion of the node's attribute name. If a local name is not defined for the reference node, the method evaluates to the empty set. =item Method: namespace() Returns the URI for the namespace of the node. Namespace URIs are defined only for element nodes and attribute nodes. The namespace URI of an element node is the namespace URI associated with the node's element type name. The namespace URI of an attribute node is the namespace URI associated with the node's attribute name. If a namespace URI is not defined for the reference node, the method evaluates to the empty set. =item Method: prefix() Returns the prefix for the node. Namespace prefixes are defined only for element nodes and attribute nodes. The namespace prefix of an element node is the shortname for the namespace of the node's element type name. The namespace prefix of an attribute node is the shortname for the namespace of the node's attribute name. If a namespace prefix is not defined for the reference node, the method evaluates to the empty set. The spec states: A node's namespace prefix may be defined within the query expression, within the document under query, or within both the query expression and the document under query. If it is defined in both places the prefixes may not agree. In this case, the prefix assigned by the query expression takes precedence. In this implementation you cannot define the namespace for a query, so this can never happen. =over 4 =item Examples: Find all unqualified book elements. Note that this does not return my:book elements: book Find all book elements with the prefix 'my'. Note that this query does not return unqualified book elements: my:book Find all book elements with a 'my' prefix that have an author subelement: my:book[author] Find all book elements with a 'my' prefix that have an author subelement with a my prefix: my:book[my:author] Find all elements with a prefix of 'my': my:* Find all book elements from any namespace: *:book Find any element from any namespace: * Find the style attribute with a 'my' prefix within a book element: book/@my:style =back All attributes of an element can be returned using @*. This is potentially useful for applications that treat attributes as fields in a record. =over 4 =item Examples: Find all attributes of the current element context: @* Find style attributes from any namespace: @*:style Find all attributes from the 'my' namespace, including unqualified attributes on elements from the 'my' namespace: @my:* =back =back =head1 Functions This section defines the functions of XQL. The spec states that: XQL defines two kinds of functions: collection functions and pure functions. Collection functions use the search context of the Invocation instance, while pure functions ignore the search context, except to evaluate the function's parameters. A collection function evaluates to a subset of the search context, and a pure function evaluates to either a constant value or to a value that depends only on the function's parameters. Don't worry if you don't get it. Just use them! =head2 Collection functions The collection functions provide access to the various types of nodes in a document. Any of these collections can be constrained and indexed. The collections return the set of children of the reference node meeting the particular restriction. =over 4 =item Function: textNode() The collection of text nodes. =item Function: comment() The collection of comment nodes. =item Function: pi() The collection of processing instruction nodes. =item Function: element( [NAME] ) The collection of all element nodes. If the optional text parameter is provided, it only returns element children matching that particular name. =item Function: attribute( [NAME] ) The collection of all attribute nodes. If the optional text parameter is provided, it only returns attributes matching that particular name. =item Function: node() The collection of all non-attribute nodes. =over 4 =item Examples: Find the second text node in each p element in the current context: p/textNode()[1] Find the second comment anywhere in the document. See Context for details on setting the context to the document root: //comment()[1] =back =back =head2 Other XQL Functions =over 4 =item Function: ancestor(QUERY) Finds the nearest ancestor matching the provided query. It returns either a single element result or an empty set []. Note that this node is never the reference node itself. =over 4 =item Examples: Find the nearest book ancestor of the current element: ancestor(book) Find the nearest ancestor author element that is contained in a book element: ancestor(book/author) =back =item Function: id(NAME) Pure function that evaluates to a set. The set contains an element node that has an 'id' attribute whose value is identical to the string that the Text parameter quotes. The element node may appear anywhere within the document under query. If more than one element node meets these criteria, the function evaluates to a set that contains the first node appearing in a document ordering of the nodes. =item Function: true() and false() Pure functions that each evaluate to a Boolean. "true()" evaluates to 'true', and "false()" evaluates to 'false'. These functions are useful in expressions that are constructed using entity references or variable substitution, since they may replace an expression found in an instance of Subquery without violating the syntax required by the instance of Subquery. They return an object of type XML::XQL::Boolean. =item Function: date(QUERY) "date" is a pure function that typecasts the value of its parameter to a set of dates. If the parameter matches a single string, the value of the function is a set containing a single date. If the parameter matches a QUERY, the value of the function is a set of dates, where the set contains one date for each member of the set to which the parameter evaluates. XQL does not define the representation of the date value, nor does it define how the function translates parameter values into dates. This implementation uses the Date::Manip module to parse dates, which accepts almost any imaginable format. See L to plug in your own Date implementation. Include the L package to add the XQL date type and the date() function, like this: use XML::XQL::Date; =item Perl builtin functions and other XQL+ functions XQL+ provides XQL function wrappers for most Perl builtin functions. It also provides other cool functions like subst(), map(), and eval() that allow you to modify documents and embed perl code. If this is still not enough, you can add your own function and methods. See L man page for details. =back =head1 Sequence Operators - ';' and ';;' The whitepaper 'The Design of XQL' by Jonathan Robie, which can be found at L describes the sequence operators ';;' (precedes) and ';' (immediately precedes.) Although these operators are not included in the XQL spec, I thought I'd add them anyway. =head2 Immediately Precedes - ';' =over 4 =item Example: With the following input:
Shady Grove Aeolian
Over the River, Charlie Dorian
Find the TD node that contains "Shady Grove" and the TD node that immediately follows it: //(TD="Shady Grove" ; TD) =back Note that in XML::DOM there is actually a text node with whitespace between the two TD nodes, but those are ignored by this operator, unless the text node has 'xml:space' set to 'preserve'. See ??? for details. =head2 Precedes - ';;' =over 4 =item Example: With the following input (from Hamlet): MARCELLUS Tis gone! Exit Ghost We do it wrong, being so majestical, To offer it the show of violence; For it is, as the air, invulnerable, And our vain blows malicious mockery. Return the STAGEDIR and all the LINEs that follow it: SPEECH//( STAGEDIR ;; LINE ) Suppose an actor playing the ghost wants to know when to exit; that is, he wants to know who says what line just before he is supposed to exit. The line immediately precedes the stagedir, but the speaker may occur at any time before the line. In this query, we will use the "precedes" operator (";;") to identify a speaker that precedes the line somewhere within a speech. Our ghost can find the required information with the following query, which selects the speaker, the line, and the stagedir: SPEECH//( SPEAKER ;; LINE ; STAGEDIR="Exit Ghost") =back =head1 Operator Precedence The following table lists operators in precedence order, highest precedence first, where operators of a given row have the same precedence. The table also lists the associated productions: Production Operator(s) ---------- ----------- Grouping ( ) Filter [ ] Subscript [ ] Bang ! Path / // Match $match$ $no_match$ =~ !~ (XQL+ only) Comparison = != < <= > >= $eq$ $ne$ $lt$ $le$ $gt$ $ge$ $ieq$ $ine$ $ilt$ $ile$ $igt$ $ige$ Intersection $intersect$ Union $union$ | Negation $not$ Conjunction $and$ Disjunction $or$ Sequence ; ;; =head1 Sample XML Document - bookstore.xml This file is also stored in samples/bookstore.xml that comes with the XML::XQL distribution. Seven Years in Trenton Joe Bob Trenton Literary Review Honorable Mention 12 History of Trenton Mary Bob Selected Short Stories of Mary Bob 55 Tracking Trenton 2.50 Trenton Today, Trenton Tomorrow Toni Bob B.A. Ph.D. Pulizer Still in Trenton Trenton Forever 6.50

It was a dark and stormy night.

But then all nights in Trenton seem dark and stormy to someone who has gone through what I have.

Trenton misery
Who's Who in Trenton Robert Bob
=head1 SEE ALSO The Japanese version of this document can be found on-line at L L, L, L and L XML-XQL-0.68/lib/XML/XQL/DirXQL.pm0100644000076500007650000005474707314122770016341 0ustar tjmathertjmather# Attibute Definitions: # # name: Text - name of file, dir, ... # ext: Text - file extension # no_ext: Text - name without ext # full: Text - full path name # abs: Text - absolute path name # # M,age: Number - Age of file (in days) # [since script started says man(perlfunc)??] # cre,create: Date (see age) # A,acc_in_days: Number - Last access time in days # acc,access: Date (see A) # set with utime() # f,is_file: Boolean # d,is_dir: Boolean # l,is_link: Boolean # p,is_pipe: Boolean # e,exists: Boolean # z,is_zero: Boolean - whether size equals zero bytes # r,readable: Boolean # w,writable: Boolean # x,executable: Boolean # o,owned: Boolean - whether it is owned (by effective uid) # #--------------------------------------------------------------------------- # Todo: # - implement abs(): absolute filepath # - support links: use lstat(), @link # - flags: -R,-W,-X,-O (by real uid/gid instead of effective uid, # -S (is_socket), -b (block special file), -c (char. special file), # -t Filehandle is opened to a tty. # -u File has setuid bit set. # -g File has setgid bit set. # -k File has sticky bit set. # -T File is a text file. # -B File is a binary file (opposite of -T). # -C inode change time in days. # set with utime() ?? # # stat() fields: # # 0 dev device number of filesystem # 1 ino inode number # 2 mode file mode (type and permissions) # add mode_str ??: "rwxr-xr--" # 3 nlink number of (hard) links to the file # 4 uid numeric user ID of file's owner # add uname # 5 gid numeric group ID of file's owner # add gname # 6 rdev the device identifier (special files only) # x 7 size total size of file, in bytes # - 8 atime last access time since the epoch # - 9 mtime last modify time since the epoch # - 10 ctime inode change time (NOT creation time!) since the epoch # 11 blksize preferred block size for file system I/O # 12 blocks actual number of blocks allocated package XML::XQL::DirXQL; use strict; use XML::XQL; use XML::XQL::Date; sub dirxql { my ($context, $list, $filepath) = @_; $filepath = XML::XQL::toList ($filepath->solve ($context, $list)); my @result; for my $file (@$filepath) { push @result, XML::XQL::DirDoc->new (Root => $file->xql_toString)->root; } \@result; } XML::XQL::defineFunction ("dirxql", \&XML::XQL::DirXQL::dirxql, 1, 1); package XML::XQL::DirNode; # extended by: DirDoc, DirAttr, DirElem (File, Dir), FileContents use vars qw{ @ISA $SEP }; @ISA = qw{ XML::XQL::Node }; # Directory path separator (default: Unix) $SEP = "/"; if ((defined $^O and $^O =~ /MSWin32/i || $^O =~ /Windows_95/i || $^O =~ /Windows_NT/i) || (defined $ENV{OS} and $ENV{OS} =~ /MSWin32/i || $ENV{OS} =~ /Windows_95/i || $ENV{OS} =~ /Windows_NT/i)) { $SEP = "\\"; # Win32 } elsif ((defined $^O and $^O =~ /MacOS/i) || (defined $ENV{OS} and $ENV{OS} =~ /MacOS/i)) { $SEP = ":"; # Mac } sub isElementNode { 0 } sub isTextNode { 0 } sub xql_parent { $_[0]->{Parent} } #sub xql_document { $_[0]->{Doc} } sub xml_xqlString { $_[0]->toString } sub xql { my $self = shift; # Odd number of args, assume first is XQL expression without 'Expr' key unshift @_, 'Expr' if (@_ % 2 == 1); my $query = new XML::XQL::Query (@_); $query->solve ($self); } sub xql_sortKey { my $key = $_[0]->{SortKey}; return $key if defined $key; $key = XML::XQL::createSortKey ($_[0]->{Parent}->xql_sortKey, $_[0]->xql_childIndex, 1); #print "xql_sortKey $_[0] ind=" . $_[0]->xql_childIndex . " key=$key str=" . XML::XQL::keyStr($key) . "\n"; $_[0]->{SortKey} = $key; } sub xql_node { my $self = shift; $self->build unless $self->{Built}; $self->{C}; } sub getChildIndex { my ($self, $kid) = @_; my $i = 0; for (@{ $self->xql_node }) { return $i if $kid == $_; $i++; } return -1; } sub xql_childIndex { $_[0]->{Parent}->getChildIndex ($_[0]); } # As it appears in the XML document sub xql_xmlString { $_[0]->toString; #?? impl. } sub create_date_from_days { my ($days, $srcNode) = @_; my $secs = int (0.5 + $days * 24 * 3600 ); my $internal = Date::Manip::DateCalc ("today", "- $secs seconds"); new XML::XQL::Date (SourceNode => $srcNode, Internal => $internal, String => $internal ); } #------ WHITESPACE STUFF (DELETE??) # Find previous sibling that is not a text node with ignorable whitespace sub xql_prevNonWS { my $self = shift; my $parent = $self->{Parent}; return unless $parent; for (my $i = $parent->getChildIndex ($self) - 1; $i >= 0; $i--) { my $node = $parent->getChildAtIndex ($i); return $node unless $node->xql_isIgnorableWS; # skip whitespace } undef; } # True if it's a Text node with just whitespace and xml::space != "preserve" sub xql_isIgnorableWS { 0; } # Whether the node should preserve whitespace # It should if it has attribute xml:space="preserve" sub xql_preserveSpace { $_[0]->{Parent}->xql_preserveSpace; } #--------------------------------------------------------------------------- package XML::XQL::DirDoc; # The Document use vars qw{ @ISA }; @ISA = qw{ XML::XQL::DirNode }; sub new { my ($type, %hash) = @_; my $self = bless \%hash, $type; $self->{Root} = "." unless exists $self->{Root}; my $dirname; if ($self->{Root} =~ /^(.+)\Q${XML::XQL::DirNode::SEP}\E(.+)$/) { $self->{Prefix} = $1; $dirname = $2; } else { $self->{Prefix} = ""; $dirname = $self->{Root}; } $self->{Dir} = new XML::XQL::Dir (TagName => $dirname, Parent => $self); $self->{Built} = 1; return $self; } sub xql { shift->root->xql (@_); } sub root { $_[0]->{Dir} } sub isElementNode { 0 } sub xql_nodeType { 9 } sub xql_childCount { 1 } sub fullname { $_[0]->{Prefix} } sub xql_sortKey { "" } sub xql_parent { undef } sub xql_nodeName { "#document" } sub depth { 0 } sub xql_node { [ $_[0]->{Dir} ] } sub xql_element { my ($self, $elem) = @_; my $dir = $self->{Dir}; if (defined $elem) { return [ $dir ] if $dir->{TagName} eq $elem; } else { return [ $dir ]; } } # By default the elements in a document don't preserve whitespace sub xql_preserveSpace { 0; } sub toString { $_[0]->root->toString; } #---------------------------------------------------------------------------- package XML::XQL::DirAttrDef; # Definitions for DirAttr nodes sub new { my ($type, %hash) = @_; bless \%hash, $type; } sub dump { print $_[0]->toString . "\n"; } sub toString { my $self = shift; print "DirAttrDef $self\n"; my $i = 0; for my $attrName ($self->in_order) { my $a = $self->{$attrName}; print "[$i] name=$attrName"; $i++; print " order=" . $a->{Order}; print " get=" . $a->{Get} if defined $a->{Get}; print " set=" . $a->{Set} if defined $a->{Set}; if (defined $a->{Alias}) { print " alias=" . join (",", @{ $a->{Alias} }); } print "\n"; } if (defined $self->{'@ALIAS'}) { print "Alias: "; my $alias = $self->{'@ALIAS'}; print join (",", map { "$_=" . $alias->{$_} } keys %$alias); print "\n"; } } sub clone { my $self = shift; my $n = new XML::XQL::DirAttrDef; $n->{'@IN_ORDER'} = [ @{ $self->{'@IN_ORDER'} } ]; for my $a (@{ $self->{'@IN_ORDER'} }) { $n->{$a} = { %{ $self->{$a} } }; $n->{$a}->{Alias} = [ @{ $self->{$a}->{Alias} } ] if defined $self->{$a}->{Alias}; } $n->{'@ALIAS'} = { %{ $self->{'@ALIAS'} } } if defined $self->{'@ALIAS'}; return $n; } sub in_order { defined $_[0]->{'@IN_ORDER'} ? @{ $_[0]->{'@IN_ORDER'} } : () } sub alias { $_[0]->{'@ALIAS'}->{$_[1]} } sub order { $_[0]->{$_[1]}->{Order} } sub get { $_[0]->{$_[1]}->{Get} } sub set { $_[0]->{$_[1]}->{Set} } sub remove_attr { my ($self, $name) = @_; next unless defined $self->{$name}; my $order = $self->{$name}->{Order}; my @in_order = $self->in_order; splice @in_order, $order, 1; # Reassign Order numbers for (my $i = 0; $i < @in_order; $i++) { $self->{$name}->{Order} = $i; } $self->{'@IN_ORDER'} = \@in_order; delete $self->{$name}; } sub define_attr { my ($self, %hash) = @_; my $name = $hash{Name}; if (defined $self->{$name}) { $hash{Order} = $self->{$name}->{Order} unless defined $hash{Order}; $self->remove_attr ($name); } my @in_order = $self->in_order; $hash{Order} = -1 if $hash{Order} >= @in_order; if ($hash{Order} == -1) { push @in_order, $name; } else { splice @in_order, $hash{Order}, 0, $name; } $self->{$name} = \%hash; # Reassign Order numbers for (my $i = 0; $i < @in_order; $i++) { $self->{$name}->{Order} = $i; } $self->{'@IN_ORDER'} = \@in_order; my @alias = defined $hash{Alias} ? @{ $hash{Alias} } : (); for (@alias) { $self->{'@ALIAS'}->{$_} = $name; } } #---------------------------------------------------------------------------- package XML::XQL::DirAttr; # Attr node use vars qw{ @ISA %GET_ATTR_FUNC %SET_ATTR_FUNC }; @ISA = qw{ XML::XQL::DirNode }; sub new { my ($type, %hash) = @_; my $self = bless \%hash, $type; $self->{xql_value} = $self->{Parent}->{AttrDef}->get ($hash{Name}); $self->{xql_setValue} = $self->{Parent}->{AttrDef}->set ($hash{Name}); $self; } sub isElementNode { 0 } sub xql_nodeType { 2 } sub xql_nodeName { $_[0]->{Name} } sub xql_childIndex { $_[0]->{Parent}->attrIndex ($_[0]->{Name}) } sub xql_childCount { 0 } sub xql_node { [] } sub is_defined { exists $_[0]->{Value} } sub create { XML::XQL::DirNode::create_date_from_days ($_[0]->{Parent}->age, $_[0]) } sub age { new XML::XQL::Number ($_[0]->{Parent}->age, $_[0]) } sub size { new XML::XQL::Text ($_[0]->{Parent}->size, $_[0]) } sub ext { new XML::XQL::Text ($_[0]->{Parent}->ext, $_[0]) } sub no_ext { new XML::XQL::Text ($_[0]->{Parent}->no_ext, $_[0]) } sub name { new XML::XQL::Text ($_[0]->{Parent}->name, $_[0]) } sub full { new XML::XQL::Text ($_[0]->{Parent}->full, $_[0]) } sub abs { new XML::XQL::Text ($_[0]->{Parent}->abs, $_[0]) } sub is_file { new XML::XQL::Boolean ($_[0]->{Parent}->is_file, $_[0]) } sub is_dir { new XML::XQL::Boolean ($_[0]->{Parent}->is_dir, $_[0]) } sub is_link { new XML::XQL::Boolean ($_[0]->{Parent}->is_link, $_[0]) } sub is_pipe { new XML::XQL::Boolean ($_[0]->{Parent}->is_pipe, $_[0]) } sub it_exists { new XML::XQL::Boolean ($_[0]->{Parent}->it_exists, $_[0]) } sub is_zero { new XML::XQL::Boolean ($_[0]->{Parent}->is_zero, $_[0]) } sub readable { new XML::XQL::Boolean ($_[0]->{Parent}->readable, $_[0]) } sub writable { new XML::XQL::Boolean ($_[0]->{Parent}->writable, $_[0]) } sub executable { new XML::XQL::Boolean ($_[0]->{Parent}->executable, $_[0]) } sub owned { new XML::XQL::Boolean ($_[0]->{Parent}->owned, $_[0]) } sub last_access_in_days { new XML::XQL::Number ($_[0]->{Parent}->last_access_in_days, $_[0]); } sub last_access { XML::XQL::DirNode::create_date_from_days ($_[0]->{Parent}->last_access_in_days, $_[0]); } sub toString { my $old = ""; #$_[0]->is_defined ? "" : " (undef)"; my $val = $_[0]->xql_value->xql_toString; #exists $_[0]->{Value} ? $_[0]->{Value}->xql_toString : "(undef)"; $_[0]->{Name} . "=\"$val$old\"" #?? encodeAttrValue } sub xql_value { $_[0]->{Value} ||= &{ $_[0]->{xql_value} } (@_); } sub xql_setValue { my ($self, $text) = @_; my $set = $_[0]->{xql_setValue}; if (defined $set) { &$set ($self, $text); } else { warn "xql_setValue not defined for DirAttr name=" . $self->{TagName}; } } sub set_name { my ($attr, $text) = @_; $attr->{Parent}->set_name ($text); } sub set_ext { my ($attr, $text) = @_; $attr->{Parent}->set_ext ($text); } sub set_no_ext { my ($attr, $text) = @_; $attr->{Parent}->set_no_ext ($text); } #---------------------------------------------------------------------------- package XML::XQL::DirElem; # File or Dir use vars qw{ @ISA $ATTRDEF }; @ISA = qw( XML::XQL::DirNode ); $ATTRDEF = new XML::XQL::DirAttrDef; $ATTRDEF->define_attr (Name => 'name', Get => \&XML::XQL::DirAttr::name, Set => \&XML::XQL::DirAttr::set_name); $ATTRDEF->define_attr (Name => 'full', Get => \&XML::XQL::DirAttr::full); $ATTRDEF->define_attr (Name => 'abs', Get => \&XML::XQL::DirAttr::abs); $ATTRDEF->define_attr (Name => 'no_ext', Get => \&XML::XQL::DirAttr::no_ext, Set => \&XML::XQL::DirAttr::set_no_ext); $ATTRDEF->define_attr (Name => 'ext', Get => \&XML::XQL::DirAttr::ext, Set => \&XML::XQL::DirAttr::set_ext); $ATTRDEF->define_attr (Name => 'age', Get => \&XML::XQL::DirAttr::age, Alias => [ 'M' ] ); $ATTRDEF->define_attr (Name => 'create', Get => \&XML::XQL::DirAttr::create, Alias => [ 'cre' ] ); $ATTRDEF->define_attr (Name => 'A', Get => \&XML::XQL::DirAttr::last_access_in_days, Alias => [ 'acc_in_days' ] ); $ATTRDEF->define_attr (Name => 'access', Get => \&XML::XQL::DirAttr::last_access, Alias => [ 'acc' ] ); # These should only be implemented for Link and Pipe resp. !! $ATTRDEF->define_attr (Name => 'l', Get => \&XML::XQL::DirAttr::is_link, Alias => [ 'is_link' ] ); $ATTRDEF->define_attr (Name => 'p', Get => \&XML::XQL::DirAttr::is_pipe, Alias => [ 'is_pipe' ] ); $ATTRDEF->define_attr (Name => 'e', Get => \&XML::XQL::DirAttr::it_exists, Alias => [ 'exists' ] ); $ATTRDEF->define_attr (Name => 'z', Get => \&XML::XQL::DirAttr::is_zero, Alias => [ 'is_zero' ] ); $ATTRDEF->define_attr (Name => 'r', Get => \&XML::XQL::DirAttr::readable, Alias => [ 'readable' ] ); $ATTRDEF->define_attr (Name => 'w', Get => \&XML::XQL::DirAttr::writable, Alias => [ 'writable' ] ); $ATTRDEF->define_attr (Name => 'x', Get => \&XML::XQL::DirAttr::executable, Alias => [ 'is_zero' ] ); $ATTRDEF->define_attr (Name => 'o', Get => \&XML::XQL::DirAttr::owned, Alias => [ 'owned' ] ); #dump_attr_def(); # mod => 0, # create => 1, # prot => 2, # protn => 3, # name => 4, # path => 5, # dir => 6, sub isElementNode { 1 } sub xql_nodeType { 1 } sub xql_nodeName { $_[0]->{TagName} } sub dump_attr_def { $ATTRDEF->dump; } sub attrNames { @{ $_[0]->{AttrDef}->{'@IN_ORDER'} } } sub hasAttr { exists $_[0]->{AttrDef}->{$_[1]} } # Attributes set/get sub full { $_[0]->fullname } sub abs { $_[0]->abs } sub no_ext { $_[0]->{TagName} } sub set_no_ext { shift->set_name (@_) } sub size { -s $_[0]->fullname } sub age { -M $_[0]->fullname } sub last_access_in_days { -A $_[0]->fullname } sub is_file { -f $_[0]->fullname } sub is_dir { -d $_[0]->fullname } sub is_link { -l $_[0]->fullname } sub is_pipe { -p $_[0]->fullname } sub it_exists { -e $_[0]->fullname } sub is_zero { -z $_[0]->fullname } sub readable { -r $_[0]->fullname } sub writable { -w $_[0]->fullname } sub executable { -x $_[0]->fullname } sub owned { -o $_[0]->fullname } sub attr_alias { return undef unless defined $_[1]; my $alias = $_[0]->{AttrDef}->alias ($_[1]); defined $alias ? $alias : $_[1]; } sub create_path # static { my ($dir, $file) = @_; if ($dir =~ /\Q${XML::XQL::DirNode::SEP}\E$/) { return "$dir$file"; } elsif ($dir eq "") # e.g. when file is root directory '/' { return $file; } else { return "$dir${XML::XQL::DirNode::SEP}$file"; } } sub fullname { my $pa = $_[0]->{Parent}->fullname; my $name = $_[0]->{TagName}; create_path ($pa, $name); } #?? same as full name - for now sub abs { shift->fullname (@_); } sub parent_dir { $_[0]->{Parent}->fullname; } # With 3 params, sets the specified attribute with $attrName to $attrValue. # With 2 params, reinitializes the specified attribute with $attrName if # it currently has a value. sub update_attr { my ($self, $attrName, $attrValue) = @_; if (@_ == 3) { my $attr = $self->getAttributeNode ($attrName); if (defined $attr && defined $attr->{Value}) { $attr->{Value} = $attrValue; } } else { return unless exists $self->{A}->{$attrName}; my $a = $self->{A}->{$attrName}; if (exists $a->{Value}) { delete $a->{Value}; $a->xql_value; # reinitialize value } } } sub set_name { my ($self, $text) = @_; my $fullName = $self->fullname; my $newName = create_path ($self->parent_dir, $text); if (rename ($fullName, $newName)) { $self->{TagName} = $text; $self->update_attr ('name', $text); $self->update_attr ('ext'); $self->update_attr ('no_ext'); return 1; } else { warn "set_name: could not rename $fullName to $newName"; return 0; } } sub ext { my $name = $_[0]->{TagName}; $name =~ /\.([^.]+)$/; # print "ext name=$name ext=$1\n"; return $1; } sub set_ext { my ($self, $text) = @_; # print "set_ext $text\n"; my $no_ext = $self->no_ext; $self->set_name (length ($text) ? "$no_ext.$text" : $no_ext); } sub no_ext { my $name = $_[0]->{TagName}; $name =~ /^(.+)\.([^.]+)$/; # print "no_ext name=$name no_ext=$1\n"; return $1; } sub set_no_ext { my ($self, $text) = @_; # print "set_no_ext $text\n"; my $ext = $self->ext; $self->set_name (length ($ext) ? "$text.$ext" : $text); } sub xql_attribute { my ($node, $attrName) = @_; if (defined $attrName) { my $attr = $node->getAttributeNode ($attrName); defined ($attr) ? [ $attr ] : []; } else { my @attr; for my $name ($node->attrNames) { push @attr, $node->getAttributeNode ($name); } \@attr; } } sub getAttributeNode { my ($self, $attrName) = @_; $attrName = $self->attr_alias ($attrName); return undef unless $self->hasAttr ($attrName); my $attr = $_[0]->{A}->{$attrName} ||= new XML::XQL::DirAttr (Parent => $self, Name => $attrName); $attr; } sub attrIndex { $_[0]->{AttrDef}->order ($_[1]); } sub toString { my ($self, $depth) = @_; my $indent = " " x $depth; my $str = $indent; my $tagName = $self->{TagName}; my $tfp = $self->tag_for_print; $str .= "<$tfp name=\"$tagName\""; for my $attrName ($self->attrNames) { next unless exists $self->{A}->{$attrName}; #?? don't print un-retrieved attributes - for now my $attr = $self->{A}->{$attrName}; next unless $attr->is_defined; $str .= " " . $attr->toString; } my $kids = $self->print_kids ? $self->xql_node : []; if (@$kids) { $str .= ">\n"; for (@$kids) { $str .= $_->toString ($depth + 1); } $str .= $indent . "\n"; } else { $str .= "/>\n"; } } #---------------------------------------------------------------------------- package XML::XQL::Dir; # Element node use vars qw{ @ISA $ATTRDEF }; @ISA = qw( XML::XQL::DirElem ); $ATTRDEF = $XML::XQL::DirElem::ATTRDEF->clone; $ATTRDEF->define_attr (Name => 'd', Get => \&XML::XQL::DirAttr::is_dir, Alias => [ 'is_dir' ] ); #dump_attr_def(); sub tag_for_print { "dir" } sub print_kids { 1 } sub dump_attr_def { $ATTRDEF->dump } sub new { my ($type, %hash) = @_; $hash{AttrDef} = $ATTRDEF; bless \%hash, $type; } sub build { my ($self) = @_; my $dirname = $self->fullname; # print "dirname=$dirname\n"; if (opendir (DIR, $dirname)) { my @kids; my @f = readdir (DIR); closedir DIR; for my $f (@f) { next if $f =~ /^..?$/; # print "dirname=$dirname f=$f\n"; my $full = defined $dirname ? "$dirname${XML::XQL::DirNode::SEP}$f" : $f; # print "dirname=$dirname full=$full\n"; if (-f $full) { push @kids, XML::XQL::File->new (Parent => $self, TagName => $f ); } elsif (-d _) { push @kids, XML::XQL::Dir->new (Parent => $self, TagName => $f ); } } $self->{C} = \@kids; $self->{Built} = 1; } else { print "can't opendir $dirname: $!"; } } sub xql_childCount { my $self = shift; $self->build unless $self->{Built}; my $ch = $self->{C}; defined $ch ? scalar(@$ch) : 0; } #---------------------------------------------------------------------------- package XML::XQL::File; # Element node use vars qw{ @ISA $ATTRDEF }; @ISA = qw( XML::XQL::DirElem ); $ATTRDEF = $XML::XQL::DirElem::ATTRDEF->clone; $ATTRDEF->define_attr (Name => 'f', Get => \&XML::XQL::DirAttr::is_file, Alias => [ 'is_file' ] ); $ATTRDEF->define_attr (Name => 'size', Get => \&XML::XQL::DirAttr::size, Alias => [ 's' ]); #dump_attr_def(); sub new { my ($type, %hash) = @_; $hash{AttrDef} = $ATTRDEF; bless \%hash, $type; } sub getChildIndex { 0 } sub xql_childCount { 1 } sub contents { $_[0]->build unless $_[0]->{Built}; $_[0]->{C}->[0] } sub xql_text { $_[0]->contents->xql_text } sub xql_rawText { $_[0]->contents->xql_text } sub tag_for_print { "file" } sub print_kids { 0 } sub dump_attr_def { $ATTRDEF->dump } sub xql_rawTextBlocks { my $self = shift; ( [ 0, 0, $self->xql_text ]) } sub xql_setValue { my ($self, $text) = @_; $self->contents->xql_setValue ($text); } sub xql_replaceBlockWithText { my ($self, $start, $end, $text) = @_; if ($start == 0 && $end == 0) { $self->xql_setValue ($text); } else { warn "xql_setText bad index start=$start end=$end"; } } sub build { my $self = shift; push @{ $self->{C} }, XML::XQL::FileContents->new (Parent => $self); $self->{Built} = 1; } #---------------------------------------------------------------------------- package XML::XQL::FileContents; # Text node use vars qw{ @ISA }; @ISA = qw{ XML::XQL::DirNode }; sub new { my ($type, %hash) = @_; bless \%hash, $type; } sub isTextNode { 1 } sub xql_nodeType { 3 } sub xql_nodeName { "#contents" } sub getChildIndex { 0 } sub xql_childCount { 0 } sub xql_rawText { $_[0]->xql_text } sub xql_text { my $self = shift; unless ($self->{Built}) { local *FILE; local $/; # slurp mode if (open (FILE, $self->{Parent}->fullname)) { $self->{Data} = ; close FILE; } else { #?? warning } $self->{Built} = 1; } $self->{Data}; } sub xql_setValue { my ($self, $text) = @_; my $filename = $self->{Parent}->fullname; local *FILE; if (open (FILE, ">$filename")) { print FILE $text; $self->{Data} = $text; $self->{Built} = 1; close FILE; } else { warn "xql_setValue could not open $filename for writing"; } } return 1; XML-XQL-0.68/lib/XML/XQL/Strict.pm0100644000076500007650000000036707314122770016473 0ustar tjmathertjmatherpackage XML::XQL::Strict; BEGIN { die "Can't 'use' or 'require' XML::XQL module before XML::XQL::Strict\nJust 'us' or 'require' XML::XQL::Strict instead" if ($XML::XQL::Included); $XML::XQL::Restricted = 1; require XML::XQL; }; 1; XML-XQL-0.68/lib/XML/XQL/Debug.pm0100644000076500007650000000423107314122770016243 0ustar tjmathertjmatherpackage XML::XQL::Debug; # Replaces the filepath separator if necessary (i.e for Macs and Windows/DOS) sub filename { my $name = shift; if ((defined $^O and $^O =~ /MSWin32/i || $^O =~ /Windows_95/i || $^O =~ /Windows_NT/i) || (defined $ENV{OS} and $ENV{OS} =~ /MSWin32/i || $ENV{OS} =~ /Windows_95/i || $ENV{OS} =~ /Windows_NT/i)) { $name =~ s!/!\\!g; } elsif ((defined $^O and $^O =~ /MacOS/i) || (defined $ENV{OS} and $ENV{OS} =~ /MacOS/i)) { $name =~ s!/!:!g; $name = ":$name"; } $name; } sub dump { new XML::XQL::Debug::Dump->pr (@_); } sub str { my $dump = new XML::XQL::Debug::Dump; $dump->pr (@_); $dump->{Str} =~ tr/\012/\n/; # for MacOS where '\012' != '\n' $dump->{Str}; } package XML::XQL::Debug::Dump; sub new { my ($class, %args) = @_; $args{Indent} = 0; $args{Str} = ""; bless \%args, $class; } sub indent { $_[0]->p (" " x $_[0]->{Indent}); } sub ip { my $self = shift; $self->indent; $self->p (@_); } sub pr { my ($self, $x) = @_; if (ref($x)) { if (ref($x) eq "ARRAY") { if (@$x == 0) { $self->ip ("\n"); return; } $self->ip ("\n"); $self->{Indent}++; for (my $i = 0; $i < @$x; $i++) { $self->ip ("\n"); $self->{Indent}++; $self->pr ($x->[$i]); $self->{Indent}--; $self->ip ("\n"); } $self->{Indent}--; $self->ip ("\n"); } else { $self->ip (""); if ($x->isa ('XML::XQL::PrimitiveType')) { $self->p ($x->xql_toString); } else { $self->p ("\n"); $self->{Indent}++; if ($x->isa ("XML::DOM::Node")) { # print node plus subnodes as XML $self->p ($x->toString); } $self->p ("\n"); $self->{Indent}--; $self->indent; } $self->p ("\n"); } } elsif (defined $x) { $self->indent; $self->p ("$x\n"); } else { $self->indent; $self->p ("\n"); } } sub p { my $self = shift; if ($self->{Dump}) { print @; } else { $self->{Str} .= join ("", @_); } } 1; XML-XQL-0.68/lib/XML/XQL/Plus.pm0100644000076500007650000004121007314122770016136 0ustar tjmathertjmather############################################################################ # Copyright (c) 1998 Enno Derksen # All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. ############################################################################ # # Extra functionality that is not part of the XQL spec # package XML::XQL; use strict; BEGIN { die "don't use/require XML::XQL::Plus, either use/require XML::XQL or XML::XQL::Strict" unless $XML::XQL::Included; }; defineComparisonOperators ( "=~" => \&XML::XQL::match_oper, "!~" => \&XML::XQL::no_match_oper, "match" => \&XML::XQL::match_oper, "no_match" => \&XML::XQL::no_match_oper, "isa" => \&XML::XQL::isa_oper, "can" => \&XML::XQL::can_oper, ); sub match_oper { my ($node, $expr) = @_; return [] if isEmptyList ($node); #?? can this happen? my $str = $node->xql_toString; $expr = prepareRvalue ($expr->solve ([$node])); return [] if isEmptyList ($expr); #?? can this happen? $expr = $expr->xql_toString; croak "bad search pattern '$expr' for =~" unless $expr =~ m!^\s*[m/]!o; my $res = eval "\$str =~ $expr"; croak "bad search pattern '$expr' for =~ operator: $@" if ($@); $res; } sub no_match_oper { my ($node, $expr) = @_; return [] if isEmptyList ($node); #?? can this happen? my $str = $node->xql_toString; $expr = prepareRvalue ($expr->solve ([$node])); return [] if isEmptyList ($expr); #?? can this happen? $expr = $expr->xql_toString; croak "bad search pattern '$expr' for !~" unless $expr =~ m!^\s*[m/]!o; my $res = eval "\$str !~ $expr"; croak "bad search pattern '$expr' for !~ operator: $@" if ($@); $res; } sub isa_oper { my ($node, $expr) = @_; return [] if isEmptyList ($node); #?? can this happen? $expr = prepareRvalue ($expr->solve ([$node])); return [] if isEmptyList ($expr); #?? can this happen? $expr = $expr->xql_toString; # Expand "number" to "XML::XQL::Number" etc. $expr = expandType ($expr); #?? I don't think empty lists are possible here. If so, add "[]" as expr ref($node) and $node->isa ($expr); } # # Not sure how useful this is, unless it supports XQL functions/methods... # sub can_oper { my ($node, $expr) = @_; return [] if isEmptyList ($node); #?? can this happen? $expr = prepareRvalue ($expr->solve ([$node])); return [] if isEmptyList ($expr); #?? can this happen? $expr = $expr->xql_toString; ref ($node) and $node->can ($expr); } sub once { my ($context, $list, $expr) = @_; $expr->solve ($context, $list); } sub xql_eval { my ($context, $list, $query, $type) = @_; # return [] if @$list == 0; $query = toList ($query->solve ($context, $list)); return [] unless @$query; if (defined $type) { $type = prepareRvalue ($type->solve ($context, $list)); $type = isEmptyList ($type) ? "Text" : $type->xql_toString; # Expand "number" to "XML::XQL::Number" etc. $type = expandType ($type); } else { $type = "XML::XQL::Text"; } my @result = (); for my $val (@$query) { $val = $val->xql_toString; $val = eval $val; #print "eval result=$val\n"; #?? check result? push @result, eval "new $type (\$val)" if defined $val; } \@result; } sub subst { my ($context, $list, $query, $expr, $repl, $mod, $mode) = @_; #?? not sure? return [] if @$list == 0; $expr = prepareRvalue ($expr->solve ($context, $list)); return [] if isEmptyList ($expr); $expr = $expr->xql_toString; $repl = prepareRvalue ($repl->solve ($context, $list)); return [] if isEmptyList ($repl); $repl = $repl->xql_toString; if (defined $mod) { $mod = prepareRvalue ($mod->solve ($context, $list)); $mod = isEmptyList ($mod) ? "" : $mod->xql_toString; } if (defined $mode) { $mode = prepareRvalue ($mode->solve ($context, $list)); $mode = isEmptyList ($mode) ? 0 : $mode->xql_toString; } else { $mode = 0; # default mode: use textBlocks for Elements } my @result = (); my $nodes = toList ($query->solve ($context, $list)); for my $node (@$nodes) { if ($mode == 0 && $node->xql_nodeType == 1) # 1: Element node { # For Element nodes, replace text in consecutive text blocks # Note that xql_rawtextBlocks, returns the blocks in reverse order, # so that the indices of nodes within previous blocks don't need # to be adjusted when a replacement occurs. my $block_matched = 0; BLOCK: for my $block ($node->xql_rawTextBlocks) { my $str = $block->[2]; my $result = eval "\$str =~ s/\$expr/\$repl/$mod"; croak "bad subst expression s/$expr/$repl/$mod: $@" if ($@); next BLOCK unless $result; $block_matched++; $node->xql_replaceBlockWithText ($block->[0], $block->[1], $str); } # Return the input parameter only if a substitution occurred push @result, $node if $block_matched; } else { my $str = $node->xql_toString; next unless defined $str; my $result = eval "\$str =~ s/\$expr/\$repl/$mod"; croak "bad subst expression s/$expr/$repl/$mod: $@" if ($@); next unless $result; #print "result=$result for str[$str] =~ s/$expr/$repl/$mod\n"; # Return the input parameter only if a substitution occurred $node->xql_setValue ($str); push @result, $node; } # xql_setValue will actually change the value of the node for an Attr, # Text, CDataSection, EntityRef or Element } \@result; } #?? redo match - what should it return? sub match { my ($context, $list, $query, $repl, $mod) = @_; return [] if @$list == 0; $query = prepareRvalue ($query->solve ($context, $list)); return [] if isEmptyList ($query); $query = $query->xql_toString; if (defined $mod) { $mod = prepareRvalue ($mod->solve ($context, $list)); $mod = isEmptyList ($mod) ? "" : $mod->xql_toString; } my $str = $list->[0]->xql_toString; return [] unless defined $str; my (@matches) = (); eval "\@matches = (\$str =~ /\$query/$mod)"; croak "bad match expression m/$query/$mod" if ($@); #?? or should I map undef to XML::XQL::Text("") ? @matches = map { defined($_) ? new XML::XQL::Text ($_) : [] } @matches; \@matches; } sub xql_map { my ($context, $list, $query, $code) = @_; #?? not sure? return [] if @$list == 0; $code = prepareRvalue ($code->solve ($context, $list)); return [] if isEmptyList ($code); $code = $code->xql_toString; my @result = (); my $nodes = toList ($query->solve ($context, $list)); for my $node (@$nodes) { my $str = $node->xql_toString; next unless defined $str; my (@mapresult) = ($str); #?? NOTE: the $code should eval "\@mapresult = map { $code } (\$str)"; croak "bad map expression '$code' ($@)" if ($@); # Return the input parameter only if a change occurred next unless $mapresult[0] eq $str; # xql_setValue will actually change the value of the node for an Attr, # Text, CDataSection, EntityRef or Element $node->xql_setValue ($str); push @result, $node; } \@result; } sub xql_new { my ($type, @arg) = @_; # Expand "number" to "XML::XQL::Number" etc. $type = expandType ($type); my $obj = eval "new $type (\@arg)"; $@ ? [] : $obj; # return empty list on exception } my $DOM_PARSER; # used by xql_document (below) sub setDocParser { $DOM_PARSER = shift; } sub xql_document { my ($docname) = @_; my $parser = $DOM_PARSER ||= new XML::DOM::Parser; my $doc; eval { $doc = $parser->parsefile ($docname); }; if ($@) { warn "xql_document: could not read XML file [$docname]: $@"; } return defined $doc ? $doc : []; } #----------- XQL+ methods -------------------------------------------- sub DOM_nodeType { my ($context, $list) = @_; return [] if @$list == 0; new XML::XQL::Number ($list->[0]->xql_DOM_nodeType, $list->[0]); } #----------- Perl Builtin Functions ---------------------------------- # Note that certain functions (like mkdir) are not considered "constant" # because we don't want their invocation values cached. (We want the # function to be called every time the Invocation is solved/evaluated.) my %PerlFunc = ( # Format: # "funcName", => [ARGCOUNT, RETURN_TYPE [, CONSTANT = 0, [QUERY_ARG = 0]]] #-------- Arithmetic Functions "abs" => [1, "Number", 1], "atan2" => [2, "Number", 1, -1], "cos" => [1, "Number", 1], "exp" => [1, "Number", 1], "int" => [1, "Number", 1], "log" => [1, "Number", 1], "rand" => [[0, 1], "Number", 0, -1], "sin" => [1, "Number", 1], "sqrt" => [1, "Number", 1], "srand" => [[0, 1], "Number", 0, -1], "time" => [0, "Number", 0, -1], #-------- Conversion Functions "chr" => [1, "Text", 1], # "gmtime" => [1, "List of Number", 1], "hex" => [1, "Number", 1], # "localtime" => [1, "List of Number", 1], "oct" => [1, "Number", 1], "ord" => [1, "Text", 1], "vec" => [3, "Number", 1], "pack" => [[1, -1], "Text", 1, -1], #?? how should this work?? # "unpack" => [2, "List of ?", 1], #-------- String Functions "chomp" => [1, "Text", 1], "chop" => [1, "Text", 1], "crypt" => [2, "Text", 1], "lindex" => [[2, 3], "Number", 1], # "index" is already taken by XQL "length" => [1, "Number", 1], "lc" => [1, "Text", 1], "lcfirst" => [1, "Text", 1], "quotemeta" => [1, "Text", 1], "rindex" => [[2, 3], "Number", 1], "substr" => [[2, 3], "Text", 1], "uc" => [1, "Text", 1], "ucfirst" => [1, "Text", 1], "reverse" => [1, "Text", 1], "sprintf" => [[1, -1], "Text", 1, -1], #-------- Array Functions "join" => [[1, -1], "Text", 1], # "split" => [[2, 3], "List of Text", 1], #-------- File Functions "chmod" => [2, "Boolean", 0, 1], "chown" => [3, "Boolean", 0, 2], "link" => [2, "Number", 0, -1], #?? no return value # "lstat" => [1, "List of Number"], "mkdir" => [2, "Boolean"], #?? or is 1 arg also allowed? "readlink" => [1, "Text"], "rename" => [2, "Boolean", 0, -1], "rmdir" => [1, "Boolean"], # "stat" => [1, "List of Number"], "symlink" => [2, "Boolean", 0, -1], "unlink" => [1, "Boolean"], "utime" => [3, "Boolean", 0, 2], "truncate" => [2, "Number"], #?? no return value #-------- System Interaction "exit" => [[0, 1], "Number"], # "glob" => [1, "List of Text"], "system" => [[1, -1], "Number", 0, -1], # "times" => [0, "List of Number"], #-------- Miscellaneous "defined" => [1, "Boolean"], # is this useful?? "dump" => [[0, 1], "Number", 0, -1], "ref" => [1, "Text"], ); #?? die, warn, croak (etc.), #?? file test (-X), tr// (same as y//) #?? array functions, sort # Generate wrapper for Perl builtin function on the fly sub generatePerlWrapper { my ($name) = @_; my $args = $PerlFunc{$name}; return undef unless defined $args; # not found my ($argCount, $returnType, $const, $queryArg) = @$args; my $funcName = $name; if ($name eq "lindex") # "index" is already taken { $funcName = "index"; } generateFunction ($name, $funcName, $returnType, $argCount, 0, $const, $queryArg); $Func{$name}; } #?? Inline functions, do they make sense? E.g. 'elem!sub("code", "arg1")' #?? Normally, user should use defineFunction, but if most of them have #?? a lot of common code, I could provide the pre- and post-code. #?? After processing the user-supplied code block, how should I convert the #?? user's result back to an Invocation result. E.g. do I get a single value #?? or a list back? defineFunction ("eval", \&XML::XQL::xql_eval, [1, 2]); defineFunction ("subst", \&XML::XQL::subst, [3, 5], 1); defineFunction ("s", \&XML::XQL::subst, [3, 5], 1); defineFunction ("match", \&XML::XQL::match, [1, 2]); defineFunction ("m", \&XML::XQL::match, [1, 2]); defineFunction ("map", \&XML::XQL::xql_map, 2, 1); defineFunction ("once", \&XML::XQL::once, 1, 1); defineMethod ("DOM_nodeType", \&XML::XQL::DOM_nodeType, 0, 0); generateFunction ("new", "XML::XQL::xql_new", "*", [1, -1], 1, 0, 1); generateFunction ("document", "XML::XQL::xql_document", "*", 1, 1, 0, 0); # doc() is an alias for document() defineFunction ("doc", \&XML::XQL::xql_wrap_document, 1, 1); #------------------------------------------------------------------------------ # The following functions were found in the XPath spec. # Found in XPath but not (yet) implemented in XML::XQL: # - type casting (string, number, boolean) - Not sure if needed... # Note that string() converts booleans to 'true' and 'false', but our # internal type casting converts it to perl values '0' and '1'... # - math (+,-,*,mod,div) - Use eval() for now # - last(), position() - Similar to end() and index() except they're 1-based # - local-name(node-set?), namespace-uri(node-set?) # - name(node-set?) - Can we pass a node-set in XQL? # - lang(string) sub xpath_concat { join ("", @_) } sub xpath_starts_with { $_[0] =~ /^\Q$_[1]\E/ } # ends-with is not part of XPath sub xpath_ends_with { $_[0] =~ /\Q$_[1]\E$/ } sub xpath_contains { $_[0] =~ /\Q$_[1]\E/ } # The following methods don't know about NaN, +/-Infinity or -0. sub xpath_floor { use POSIX; POSIX::floor ($_[0]) } sub xpath_ceiling { use POSIX; POSIX::ceil ($_[0]) } sub xpath_round { use POSIX; POSIX::floor ($_[0] + 0.5) } # Note that the start-index is 1-based in XPath sub xpath_substring { defined $_[2] ? substr ($_[0], $_[1] - 1, $_[2]) : substr ($_[0], $_[1] - 1) } sub xpath_substring_before { my $i = index ($_[0], $_[1]); $i == -1 ? undef : substr ($_[0], 0, $i) } sub xpath_substring_after { my $i = index ($_[0], $_[1]); $i == -1 ? undef : substr ($_[0], $i + length($_[1])) } # Note that d,c,s are tr/// modifiers. Also can't use open delimiters i.e. {[(< my @TR_DELIMITERS = split //, "/!%^&*)-_=+|~]}'\";:,.>/?abefghijklmnopqrtuvwxyz"; sub xpath_translate { my ($str, $from, $to) = @_; my $delim; for my $d (@TR_DELIMITERS) { if (index ($from, $d) == -1 && index ($to, $d) == -1) { $delim = $d; last; } } die "(xpath_)translate: can't find suitable 'tr' delimiter" unless defined $delim; # XPath defines that if length($from) > length($to), characters in $from # for which there is no match in $to, should be deleted. # (So we must use the 's' modifier.) eval "\$str =~ tr$delim$from$delim$to${delim}d"; $str; } sub xpath_string_length { my ($context, $list, $text) = @_; if (defined $text) { $text = XML::XQL::prepareRvalue ($text->solve ($context, $list)); return [] unless defined $text; return new XML::XQL::Number (length $text->xql_toString, $text->xql_sourceNode); } else { return [] if @$list == 0; my @result; for my $node (@$list) { push @result, new XML::XQL::Number (length $node->xql_toString, $node); } return \@result; } } sub _normalize { $_[0] =~ s/\s+/ /g; $_[0] =~ s/^\s+//; $_[0] =~ s/\s+$//; $_[0]; } sub xpath_normalize_space { my ($context, $list, $text) = @_; return [] if @$list == 0; if (defined $text) { $text = XML::XQL::prepareRvalue ($text->solve ($context, $list)); return [] unless defined $text; return new XML::XQL::Text (_normalize ($text->xql_toString), $text->xql_sourceNode); } else { my @result; for my $node (@$list) { push @result, new XML::XQL::Text (_normalize ($node->xql_toString), $node); } return \@result; } } sub xpath_sum { my ($context, $list, $expr) = @_; return [] if @$list == 0; #?? or return Number(0) ? my $sum = 0; $expr = XML::XQL::toList ($expr->solve ($context, $list)); for my $r (@{ $expr }) { $sum += $r->xql_toString; } return new XML::XQL::Number ($sum, undef); } generateFunction ("round", "XML::XQL::xpath_round", "Number", 1, 1); generateFunction ("floor", "XML::XQL::xpath_floor", "Number", 1, 1); generateFunction ("ceiling", "XML::XQL::xpath_ceiling", "Number", 1, 1); generateFunction ("concat", "XML::XQL::xpath_concat", "Text", [2, -1], 1); generateFunction ("starts-with", "XML::XQL::xpath_starts_with", "Boolean", 2, 1); generateFunction ("ends-with", "XML::XQL::xpath_ends_with", "Boolean", 2, 1); generateFunction ("contains", "XML::XQL::xpath_contains", "Boolean", 2, 1); generateFunction ("substring-before", "XML::XQL::xpath_substring_before", "Text", 2, 1); generateFunction ("substring-after", "XML::XQL::xpath_substring_after", "Text", 2, 1); # Same as Perl substr() except index is 1-based generateFunction ("substring", "XML::XQL::xpath_substring", "Text", [2, 3], 1); generateFunction ("translate", "XML::XQL::xpath_translate", "Text", 3, 1); defineMethod ("string-length", \&XML::XQL::xpath_string_length, [0, 1], 1); defineMethod ("normalize-space", \&XML::XQL::xpath_normalize_space, [0, 1], 1); defineFunction ("sum", \&XML::XQL::xpath_sum, 1, 1); 1; # module return code XML-XQL-0.68/lib/XML/XQL.pm0100644000076500007650000027600607611625062015232 0ustar tjmathertjmather############################################################################ # Copyright (c) 1998,1999 Enno Derksen # All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. ############################################################################ # # To do (in no particular order): # # - Element tag names that are the same as a XQL keyword (e.g. "or", "not", ..) # are currently not supported. The parser and lexer needs to be smarter and # know what context they are in. # - output using xql:result etc. # - xml:space=preserve still needs to be adhered to in text() etc. # - I already added xql_preserveSpace. Still need to use it in (raw)text() etc. # - XQL functions (like value()) should probably work on input lists > 1 node # (The code was changed, but it needs to be tested. ancestor() wasn't fixed) # - verify implementation of xql_namespace # - verify implementation of end, index # - check passing of context to the solve() methods # - functions/methods may be wrong. They receive the entire LHS set, # so count() is right, but the rest may be wrong! # - may need to use different comment delimiters, '#' may be used in future XQL # definition (according to Joe Lapp, one of the XQL spec authors) # - caching of Node xql_values (?) # - finish the Date class # - discuss which classes: Date, Time, and/or DateTime ? # - conversion of Query result to Perl primitives, i.e. how do we return the # result of a query. # - add support for ordering/formatting the query results, see XML-QL # - discuss typecasting mechanism # - error reporting mechanism # - yyerror handler doesn't seem to work # - passing intermediate exceptions ($@) to the user # - more debugging support # - subst, map etc. # - use rawText for Nodes? # - recurse or not? # - text/rawText default - recurse or not? # - what should default value() implementation use? # - check if all Syntactic Constraints in XQL spec are implemented # - support all node types, i.e. Notation, Attlist etc. # - sorting in 'document order' doesn't work yet for 'other' DOM nodes # - generateFunction - support functions that return lists? # - match() function - what should it return? # - keeping track of reference nodes not always done right # - also think about Perl builtin functions # - conversion to Perl number throws warnings with -w (in comparisons etc.) # - sorting # - add sorting by attribute name (within same element) # (or other criteria) # - optional sorting in $union$ ? # - could add a flag that says "don't worry about document order for $union$" # - user defined sort? # - OPTIMIZE! # - Subscript operator # - Filter operator # - etc. package XML::XQL; use strict; use Carp; use XML::RegExp; use vars qw( @EXPORT $VERSION $ContextStart $ContextEnd $BoldOn $BoldOff %Func %Method %FuncArgCount %AllowedOutsideSubquery %ConstFunc %ExpandedType $Restricted $Included $ReXQLName %CompareOper $Token_q $Token_qq $LAST_SORT_KEY ); @EXPORT = qw( $VERSION $Restricted $Included ); BEGIN { $VERSION = '0.68'; die "XML::XQL is already used/required" if defined $Included; $Included = 1; # From XQL spec (The '-' was added to allow XPath style function names.) $ReXQLName = "(?:[-a-zA-Z_]+\\w*)"; $Token_q = undef; $Token_qq = undef; $Restricted = 0 unless defined $Restricted; if (not $Restricted) { # Allow names with Perl package prefixes $ReXQLName = "(?:$ReXQLName(?:::$ReXQLName)*)"; # Support q// and qq// strings $Token_q = "q"; $Token_qq = "qq"; } }; # To save the user some typing for the simplest cases sub solve { my ($expr, @args) = @_; my $query = new XML::XQL::Query (Expr => $expr); my @result = $query->solve (@args); $query->dispose; @result; } #---------- Parser related stuff ---------------------------------------------- # Find (nested) closing delimiter in q{} or qq{} strings sub parse_q { my ($qname, $q, $str, $d1, $d2) = @_; my ($match) = ""; my ($found); while ($str =~ /^([^$d1$d2]*)($d1|($d2))(.*)/s) { defined ($3) and return ($4, $match . $1); # $d2 found # match delimiters recursively $match .= $1 . $2; ($str, $found) = parse_q ($qname, $q, $4, $d1, $d2); $match .= $found . $d2; } XML::XQL::parseError ("no $qname// closing delimiter found near '$q$d1'"); } # To support nested delimiters in q{} and qq() strings my %MatchingCloseDelim = ( '{' => '}', '(' => ')', '<' => '>', '[' => ']' ); sub Lexer { my($parser)=shift; exists($parser->YYData->{LINE}) or $parser->YYData->{LINE} = 1; $parser->YYData->{INPUT} or return('', undef); print "Lexer input=[" . $parser->YYData->{INPUT} . "]\n" if $parser->{yydebug}; if ($Restricted) { # strip leading whitespace $parser->YYData->{INPUT} =~ s/^\s*//; } else { # strip leading whitespace and comments $parser->YYData->{INPUT} =~ s/^(\s|#.*)*//; } for ($parser->YYData->{INPUT}) { s#^"([^"]*)"##o and return ('TEXT', $1); s#^'([^']*)'##o and return ('TEXT', $1); if (not $Restricted) { # Support q// and qq// string delimiters for my $qname ('q', 'qq') { my ($q) = $parser->{Query}->{$qname}; if (defined ($q) and s/^$q(\[\(\{\<#!=-\+|'":;\.,\?\/!@\%^\*)//) { my ($d1, $d2) = ($1, $MatchingCloseDelim{$1}); my ($str); if (defined $d2) { ($parser->YYData->{INPUT}, $str) = parse_q ( $qname, $q, $_, $d1, $d2); } else # close delim is same open delim { $d2 = $d1; s/([^$d2])*$d2// or XML::XQL::parseError ( "no $qname// closing delimiter found near '$q$d1'"); $str = $1; } return ('TEXT', eval "$q$d1$str$d2"); } } } s/^(-?\d+\.(\d+)?)// and return ('NUMBER', $1); s/^(-?\d+)// and return ('INTEGER', $1); s/^(\$|\b)(i?(eq|ne|lt|le|gt|ge))\1(?=\W)//i and return ('COMPARE', "\L$2"); s/^((\$|\b)(any|all|or|and|not|to|intersect)\2)(?=\W)//i and return ("\L$3", $1); s/^((\$|\b)union\2(?=\W)|\|)//i and return ('UnionOp', $1); s/^(;;?)// and return ('SeqOp', $1); if (not $Restricted) { s/^(=~|!~)// and return ('MATCH', $1); s/^\$((no_)?match)\$//i and return ('MATCH', "\L$1"); s/^\$($ReXQLName)\$//o and return ('COMPARE', $1); } s/^(=|!=|<|<=|>|>=)// and return ('COMPARE', $1); s!^(//|/|\(|\)|\.\.?|@|\!|\[|\]|\*|:|,)!! and return ($1, $1); s/^($ReXQLName)\s*\(//o and return ('XQLName_Paren', $1); s/^($XML::RegExp::Name)//o and return ('NCName', $1); } } #------ end Parser related stuff ---------------------------------------------- # Converts result from a Disjunction to a 0 or 1. # If it's a XML::XQL::Boolean, its value is returned. # If it's an empty list it returns 0. # If it's a node or a Text or Number, it returns 1. # If it's a list with 1 or more elements, it returns 1 if at least one # element evaluates to 1 (with toBoolean) sub toBoolean # static method { my $arg = shift; my $type = ref ($arg); if ($type eq "ARRAY") { for my $n (@$arg) { return 1 if toBoolean ($n); } return 0; } return $arg->xql_toBoolean; } sub listContains { my ($list, $x) = @_; #?? $n should be a PrimitiveType or an XML Node for my $y (@$list) { #?? return 1 if $x == $y; if (ref($x) eq ref($y)) # same object class { my ($src1, $src2) = ($x->xql_sourceNode, $y->xql_sourceNode); next if ((defined $src1 or defined $src2) and $src1 != $src2); return ($x == $y) if (UNIVERSAL::isa ($x, 'XML::XQL::Node')); return 1 if $x->xql_eq ($y); } } 0; } sub toList { my $r = shift; (ref ($r) eq "ARRAY") ? $r : [ $r ]; } # Prepare right hand side for a comparison, i.e. # turn it into a single value. # If it is a list with 2 or more values, it croaks. sub prepareRvalue { my $r = shift; if (ref ($r) eq "ARRAY") { # more than 1 value gives a runtime error (as per Joe Lapp) croak "bad rvalue $r" if @$r > 1; $r = $r->[0]; } if (ref ($r) and $r->isa ('XML::XQL::Node')) { $r = $r->xql_value; } $r; } sub trimSpace { $_[0] =~ s/^\s+//; $_[0] =~ s/\s+$//; $_[0]; } # Assumption: max. 32768 (2**15 = 2**($BITS-1)) children (or attributes) per node # Use setMaxChildren() to support larger offspring. my $BITS = 16; $LAST_SORT_KEY = (2 ** $BITS) - 1; # Call with values: $max = 128 * (256**N), where N=0, 1, 2, ... sub setMaxChildren { my $max = shift; my $m = 128; $BITS = 8; while ($max > $m) { $m = $m * 256; $BITS += 8; } $LAST_SORT_KEY = (2 ** $BITS) - 1; } sub createSortKey { # $_[0] = parent sort key, $_[1] = child index, # $_[2] = 0 for attribute nodes, 1 for other node types my $vec = ""; vec ($vec, 0, $BITS) = $_[1]; vec ($vec, 7, 1) = $_[2] if $_[2]; # set leftmost bit (for non-attributes) $_[0] . $vec; } #--------------- Sorting source nodes ---------------------------------------- # Sort the list by 'document order' (as per the XQL spec.) # Values with an associated source node are sorted by the position of their # source node in the XML document. # Values without a source node are placed at the end of the resulting list. # The source node of an Attribute node, is its (parent) Element node # (per definition.) The source node of the other types of XML nodes, is itself. # The order for values with the same source node is undefined. sub sortDocOrder { #?? or should I just use: sort { $a->xql_sortKey cmp $b->xql_sortKey } my $list = shift; #print "before---\n"; #for (@$list) #{ # print "key=" . keyStr($_->xql_sortKey) . " node=" . $_->getTagName . " id=" . $_->getAttribute('id') . "\n"; #} @$list = map { $_->[1] } # 3) extract nodes sort { $a->[0] cmp $b->[0] } # 2) sort by sortKey map { [$_->xql_sortKey, $_] } # 1) make [sortKey,node] records @$list; #print "after---\n"; #for (@$list) #{ # print "key=" . keyStr($_->xql_sortKey) . " node=" . $_->getTagName . " id=" . $_->getAttribute('id') . "\n"; #} $list; } # Converts sort key from createSortKey in human readable form # For debugging only. sub keyStr { my $key = shift; my $n = $BITS / 8; my $bitn = 2 ** ($BITS - 1); my $str; for (my $i = 0; $i < length $key; $i += $n) { my $dig = substr ($key, $i, $n); my $v = vec ($dig, 0, $BITS); my $elem = 0; if ($v >= $bitn) { $v -= $bitn; $elem = 1; } $str .= "/" if defined $str; $str .= "@" unless $elem; $str .= $v; } $str; } sub isEmptyList { my $list = shift; (ref ($list) eq "ARRAY") && (@$list == 0); } # Used by Element and Attribute nodes sub buildNameSpaceExpr { my ($nameSpace, $name) = @_; $name = ".*" if $name eq "*"; if (defined $nameSpace) { $nameSpace = ".*" if $nameSpace eq "*"; "^$nameSpace:$name\$"; } else { "^$name\$"; } } sub prepareForCompare { my ($left, $right) = @_; my $leftType = $left->xql_primType; if ($leftType == 0) # Node { $left = $left->xql_value; $leftType = $left->xql_primType; } my $rightType = $right->xql_primType; if ($rightType == 0) # Node { $right = $right->xql_value; $rightType = $right->xql_primType; } # Note: reverse the order if $leftType < $rightType ($leftType < $rightType, $left, $right); } sub xql_eq { my ($left, $right, $ignoreCase) = @_; my $reverse; ($reverse, $left, $right) = prepareForCompare ($left, $right); $reverse ? $right->xql_eq ($left, $ignoreCase) : $left->xql_eq ($right, $ignoreCase); } sub xql_ne { my ($left, $right, $ignoreCase) = @_; my $reverse; ($reverse, $left, $right) = prepareForCompare ($left, $right); $reverse ? $right->xql_ne ($left, $ignoreCase) : $left->xql_ne ($right, $ignoreCase); } sub xql_lt { my ($left, $right, $ignoreCase) = @_; my $reverse; ($reverse, $left, $right) = prepareForCompare ($left, $right); $reverse ? $right->xql_ge ($left, $ignoreCase) : $left->xql_lt ($right, $ignoreCase); } sub xql_le { my ($left, $right, $ignoreCase) = @_; my $reverse; ($reverse, $left, $right) = prepareForCompare ($left, $right); $reverse ? $right->xql_gt ($left, $ignoreCase) : $left->xql_le ($right, $ignoreCase); } sub xql_gt { my ($left, $right, $ignoreCase) = @_; my $reverse; ($reverse, $left, $right) = prepareForCompare ($left, $right); $reverse ? $right->xql_le ($left, $ignoreCase) : $left->xql_gt ($right, $ignoreCase); } sub xql_ge { my ($left, $right, $ignoreCase) = @_; my $reverse; ($reverse, $left, $right) = prepareForCompare ($left, $right); $reverse ? $right->xql_lt ($left, $ignoreCase) : $left->xql_ge ($right, $ignoreCase); } sub xql_ieq { xql_eq (@_, 1); } sub xql_ine { xql_ne (@_, 1); } sub xql_ilt { xql_lt (@_, 1); } sub xql_igt { xql_gt (@_, 1); } sub xql_ige { xql_ge (@_, 1); } sub xql_ile { xql_le (@_, 1); } sub tput { # Let me know if I need to add other systems for which 'tput' is not # available. return undef unless defined $ENV{TERM}; if ($^O =~ /Win|MacOS/) { return ""; } else { my $c = shift; # tput is only available on Unix systems. # Calling `tput ...` on Windows generates warning messages # that can not be suppressed. return `tput $c`; } } # Underline the query subexpression that fails (if tput exists) $ContextStart = tput ('smul') || ">>"; # smul: underline on $ContextEnd = tput ('rmul') || "<<"; # rmul: underline off # Used for making the significant keyword of a subexpression bold, e.g. "$and$" $BoldOn = tput ('bold') || ""; $BoldOff = tput ('rmul') || ""; $BoldOff .= tput ('smul') || ""; # rmul reverts the string back to normal text, smul makes it underlined again, # so the rest of the subexpresion will be underlined. sub setErrorContextDelimiters { ($ContextStart, $ContextEnd, $BoldOn, $BoldOff) = @_; } sub delim { my ($str, $node, $contextNode) = @_; if ($node == $contextNode) { $str =~ s/\016([^\017]*)\017/$BoldOn$1$BoldOff/g; "$ContextStart$str$ContextEnd"; } else { $str =~ s/\016([^\017]*)\017/$1/g; $str; } } sub bold { my $x = shift; "\016$x\017"; # arbitrary ASCII codes } sub parseError { my ($msg) = @_; print STDERR $msg . "\n"; croak $msg; } # Builtin XQL functions (may not appear after Bang "!") %Func = ( ancestor => \&XML::XQL::Func::ancestor, attribute => \&XML::XQL::Func::attribute, comment => \&XML::XQL::Func::comment, element => \&XML::XQL::Func::element, id => \&XML::XQL::Func::id, node => \&XML::XQL::Func::node, pi => \&XML::XQL::Func::pi, textNode => \&XML::XQL::Func::textNode, true => \&XML::XQL::Func::true, false => \&XML::XQL::Func::false, # NOTE: date() is added with: use XML::XQL::Date; ); # Builtin XQL methods (may appear after Bang "!") %Method = ( baseName => \&XML::XQL::Func::baseName, count => \&XML::XQL::Func::count, end => \&XML::XQL::Func::end, 'index' => \&XML::XQL::Func::xql_index, namespace => \&XML::XQL::Func::namespace, nodeName => \&XML::XQL::Func::nodeName, nodeType => \&XML::XQL::Func::nodeType, nodeTypeString => \&XML::XQL::Func::nodeTypeString, prefix => \&XML::XQL::Func::prefix, text => \&XML::XQL::Func::text, rawText => \&XML::XQL::Func::rawText, value => \&XML::XQL::Func::value, ); # Number of arguments for builtin XQL functions: # Value is either an integer or a range. Value is 0 if not specified. # Range syntax: # # range ::= '[' start ',' end [ ',' start ',' end ]* ']' # start ::= INTEGER # end ::= INTEGER | '-1' ('-1' means: "or more") # # Example: [2, 4, 7, 7, 10, -1] means (2,3,4,7,10,11,...) %FuncArgCount = ( ancestor => 1, attribute => [0,1], count => [0,1], # date => 1, element => [0,1], id => 1, text => [0,1], rawText => [0,1], ); %AllowedOutsideSubquery = ( ancestor => 1, attribute => 1, comment => 1, element => 1, id => 1, node => 1, pi => 1, textNode => 1, #?? what about subst etc. ); # Functions that always return the same thing if their arguments are constant %ConstFunc = ( true => 1, false => 1, # date => 1, ); %ExpandedType = ( "boolean" => "XML::XQL::Boolean", "text" => "XML::XQL::Text", "number" => "XML::XQL::Number", "date" => "XML::XQL::Date", "node" => "XML::XQL::Node", ); sub expandType { my ($type) = @_; # Expand "number" to "XML::XQL::Number" etc. my $expanded = $ExpandedType{"\L$type"}; defined $expanded ? $expanded : $type; } sub defineExpandedTypes { my (%args) = @_; while (my ($key, $val) = each %args) { # Convert keys to lowercase $ExpandedType{"\L$key"} = $val; } } sub generateFunction { my ($name, $funcName, $returnType, $argCount, $allowedOutsideSubquery, $const, $queryArg) = @_; $argCount = 0 unless defined $argCount; $allowedOutsideSubquery = 1 unless defined $allowedOutsideSubquery; $const = 0 unless defined $const; $queryArg = 0 unless defined $queryArg; $returnType = expandType ($returnType); my $wrapperName = "xql_wrap_$name"; $wrapperName =~ s/\W/_/g; # replace colons etc. my $func; my $code = <solve (\$context, \$list)); } else { \$arg[\$i] = XML::XQL::prepareRvalue (\$arg[\$i]->solve (\$context, \$list)); return [] if XML::XQL::isEmptyList (\$arg[\$i]); \$arg[\$i] = \$arg[\$i]->xql_toString; } } END_CODE if (ref ($argCount) eq "ARRAY" && @$argCount == 2 && $argCount->[0] == $argCount->[1]) { $argCount = $argCount->[0]; } if ($queryArg != -1) { $code .=<xql_toString; END_CODE } if (ref ($argCount) ne "ARRAY") { $code .= " my \$result = $funcName ("; for my $i (0 .. $argCount-1) { $code .= ", " if $i; $code .= "\$arg[$i]"; } $code .= ");\n"; } elsif (@$argCount == 2) { my ($start, $end) = ($argCount->[0], $argCount->[1]); if ($end == -1) { $code .= " my \$result = $funcName ("; for my $i (0 .. ($start - 1)) { $code .= ", " if $i; $code .= "\$arg[$i]"; } $code .= ", \@arg[" . $start . " .. \$#arg]);\n"; } else { $code .= " my \$n = \@arg;\n my \$result;\n "; for my $j ($argCount->[0] .. $argCount->[1]) { $code .= " els" unless $j == $argCount->[0]; $code .= ($j == $argCount->[1] ? "e\n" : "if (\$n == $j)\n"); $code .= " {\n \$result = $funcName ("; for my $i (0 .. $j-1) { $code .= ", " if $i; $code .= "\$arg[$i]"; } $code .= ");\n }\n"; } } } else #?? what now... { $code .= " my \$result = $funcName (\@arg);\n"; } if ($returnType eq "*") # return result as is { $code .= " \$result = [] unless defined \$result;\n"; } else { $code .= " \$result = defined \$result ? new $returnType (\$result) : [];\n"; } if ($queryArg == -1) { $code .= " \$result;\n}\n"; } else { $code .= " push \@result, \$result;\n }\n \\\@result;\n}\n"; } $code .= "\$func = \\\&$wrapperName;"; #print "CODE=$code\n"; eval "$code"; if ($@) { croak "generateFunction failed for $funcName: $@\n"; } defineFunction ($name, $func, $argCount, $allowedOutsideSubquery, $const); } sub defineFunction { my ($name, $func, $argCount, $allowedOutside, $const) = @_; $Func{$name} = $func; $FuncArgCount{$name} = $argCount; $AllowedOutsideSubquery{$name} = 1 if $allowedOutside; $ConstFunc{$name} = $const; } sub defineMethod { my ($name, $func, $argCount, $allowedOutside) = @_; $Method{$name} = $func; $FuncArgCount{$name} = $argCount; $AllowedOutsideSubquery{$name} = 1 if $allowedOutside; } %CompareOper = ( 'eq' => \&XML::XQL::xql_eq, 'ne' => \&XML::XQL::xql_ne, 'le' => \&XML::XQL::xql_le, 'ge' => \&XML::XQL::xql_ge, 'gt' => \&XML::XQL::xql_gt, 'lt' => \&XML::XQL::xql_lt, 'ieq' => \&XML::XQL::xql_ieq, 'ine' => \&XML::XQL::xql_ine, 'ile' => \&XML::XQL::xql_ile, 'ige' => \&XML::XQL::xql_ige, 'igt' => \&XML::XQL::xql_igt, 'ilt' => \&XML::XQL::xql_ilt, '=' => \&XML::XQL::xql_eq, '!=' => \&XML::XQL::xql_ne, '>' => \&XML::XQL::xql_gt, '>=' => \&XML::XQL::xql_ge, '<' => \&XML::XQL::xql_lt, '<=' => \&XML::XQL::xql_le, ); sub defineComparisonOperators { my (%args) = @_; %CompareOper = (%CompareOper, %args); } sub defineTokenQ { $Token_q = $_[0]; } sub defineTokenQQ { $Token_qq = $_[0]; } my %ElementValueType = (); my $ElementValueTypeCount = 0; sub elementValue { my ($elem) = @_; #?? raw text/recursive ? return new XML::XQL::Text ($elem->xql_text, $elem) if $ElementValueTypeCount == 0; # user hasn't defined any types my $tagName = $elem->xql_nodeName; my $func = $ElementValueType{$tagName}; return new XML::XQL::Text ($elem->xql_text, $elem) unless defined $func; &$func ($elem, $tagName); } sub defineElementValueConvertor { my ($elemTagName, $func) = @_; my $prev = defined $ElementValueType{$elemTagName}; $ElementValueType{$elemTagName} = $func; if (defined $func != $prev) { defined $func ? $ElementValueTypeCount++ : $ElementValueTypeCount--; } } my %AttrValueType = (); my $AttrValueTypeCount = 0; sub attrValue { my ($attr) = @_; #?? raw text/recursive ? return new XML::XQL::Text ($attr->xql_text, $attr) if $AttrValueTypeCount == 0; # user hasn't defined any types my $elem = $attr->xql_parent->xql_nodeName; my $attrName = $attr->xql_nodeName; my $func = $AttrValueType{"$elem $attrName"}; if (not defined $func) { $elem = "*"; $func = $AttrValueType{"$elem $attrName"}; } return new XML::XQL::Text ($attr->xql_text, $attr) unless defined $func; &$func ($attr, $attrName, $elem); } sub defineAttrValueConvertor { my ($elemTagName, $attrName, $type) = @_; my $both = "$elemTagName $attrName"; my $prev = defined $AttrValueType{$both}; $AttrValueType{$both} = $type; if (defined $type != $prev) { defined $type ? $AttrValueTypeCount++ : $AttrValueTypeCount--; } } #=== debug sub exception { my ($ex) = @_; print "Exception: $ex\n" if $ex; $ex; } sub d { my $n = shift; my $type = ref $n; if ($type eq "ARRAY") { my $str = ""; for my $i (@$n) { $str .= ", " unless $str eq ""; $str .= d ($i); } return "[$str]"; } elsif ($type eq "HASH") { my $str = ""; while (my ($key, $val) = %$n) { $str .= ", " unless $str eq ""; $str .= $key . " => " . d ($val); } return "{$str}"; } elsif ($type) { return $n->xql_contextString if ($n->isa ('XML::XQL::Operator')); return "${type}\[" . $n->xql_toString . "]" if $n->isa ('XML::XQL::PrimitiveType'); # return "${type}\[" . $n->toString . "]" if $n->isa ('XML::DOM::Element'); } $n; } package XML::XQL::Query; use Carp; use XML::XQL::Parser; use vars qw( %Func %FuncArgCount ); my $parser = new XML::XQL::Parser; # This is passed as 'yyerror' to YYParse sub Error { my($parser) = shift; print STDERR "Error in Query Expression near: " . $parser->YYData->{INPUT} . "\n"; } sub defineFunction { my ($self, $name, $func, $argCount, $allowedOutside, $const) = @_; $self->{Func}->{$name} = $func; $self->{FuncArgCount}->{$name} = $argCount; $self->{AllowedOutsideSubquery}->{$name} = 1 if $allowedOutside; $self->{ConstFunc} = $const; } sub defineMethod { my ($self, $name, $func, $argCount, $allowedOutside) = @_; $self->{Method}->{$name} = $func; $self->{FuncArgCount}->{$name} = $argCount; $self->{AllowedOutsideSubquery}->{$name} = 1 if $allowedOutside; } sub defineComparisonOperators { my ($self, %args) = @_; $self->{CompareOper} = \%args; } sub defineTokenQ { $_[0]->{'q'} = $_[1]; } sub defineTokenQQ { $_[0]->{'qq'} = $_[1]; } sub new { my ($class, %args) = @_; croak "no Expr specified" unless defined $args{Expr}; my $self = bless \%args, $class; my $error = $self->{'Error'} || \&XML::XQL::Query::Error; my $debug = defined ($self->{Debug}) ? $self->{Debug} : 0; # 0x17; $self->{'q'} = $XML::XQL::Token_q unless exists $self->{'q'}; $self->{'qq'} = $XML::XQL::Token_qq unless exists $self->{'qq'}; # Invoke the query expression parser $parser->YYData->{INPUT} = $self->{Expr}; $parser->{Query} = $self; $self->{Tree} = $parser->YYParse (yylex => \&XML::XQL::Lexer, yyerror => $error, yydebug => $debug); # Nothing but whitespace should be left over if ($parser->YYData->{INPUT} !~ /^\s*$/) { XML::XQL::parseError ("Error when parsing expression. Unexpected characters at end of expression [" . $parser->YYData->{INPUT} . "]") } XML::XQL::parseError ("Error when parsing expression") unless defined $self->{Tree}; $self->{Tree}->{Query} = $self; $self->{Tree}->xql_check (0, 0); # inSubQuery=0, inParam=0 print "Expression parsed successfully\n" if $debug; $self; } sub dispose { my $self = shift; undef $self->{Tree}->{Query}; $self->{Tree}->dispose; delete $self->{Tree}; } sub isNodeQuery { $_[0]->{NodeQuery}; } sub solve { my ($self, @list) = @_; my $context = undef; # clear cached "once" values $self->{Tree}->xql_prepCache; my $result = $self->{Tree}->solve ($context, \@list); ref ($result) eq "ARRAY" ? @$result : ($result); } sub toString { $_[0]->{Expr}; } sub toDOM { my ($self, $doc) = @_; my $root = $doc->createElement ("XQL"); $doc->appendChild ($root); $root->appendChild ($self->{Tree}->xql_toDOM ($doc)); $doc; } sub findComparisonOperator { my ($self, $name) = @_; my $cmp; if (exists $self->{CompareOper}->{$name}) { $cmp = $self->{CompareOper}->{$name}; } else { $cmp = $XML::XQL::CompareOper{$name}; } if (not defined $cmp) { XML::XQL::parseError ("undefined comparison operator '$name'"); } $cmp; } # Return function pointer. Croak if wrong number of arguments. sub findFunctionOrMethod { my ($self, $name, $args) = @_; my $func; my $type = "function"; if (exists $self->{Func}->{$name}) { $func = $self->{Func}->{$name}; } elsif (exists $self->{Method}->{$name}) { $func = $self->{Method}->{$name}; $type = "method"; } elsif (defined $XML::XQL::Func{$name}) { $func = $XML::XQL::Func{$name}; } elsif (defined $XML::XQL::Method{$name}) { $func = $XML::XQL::Method{$name}; $type = "method"; } elsif (not $XML::XQL::Restricted) { $func = XML::XQL::generatePerlWrapper ($name); } XML::XQL::parseError ("undefined function/method '$name' in query '" . $self->toString . "'") unless defined &$func; my $funcArgCount = $self->{FuncArgCount}->{$name} || $XML::XQL::FuncArgCount{$name} || 0; # Check number of args my $nargs = @$args; #print "$args " . XML::XQL::d($args) . "\n"; my $ok = 0; if (ref ($funcArgCount) eq "ARRAY") { my $i = 0; my $n = @$funcArgCount; while ($i < $n) { my $s = $funcArgCount->[$i++]; my $e = $funcArgCount->[$i++] || $s; # same as $s if odd #args if ($nargs >= $s && ($e == -1 || $nargs <= $e)) { $ok = 1; # found it last; } } } else { $ok = ($nargs eq $funcArgCount); } XML::XQL::parseError ("wrong number of args ($nargs) for $type $name in query '" . $self->toString . "', it should be " . XML::XQL::d($funcArgCount)) if not $ok; return ($func, $type); } sub isAllowedOutsideSubquery { my ($self, $funcName) = @_; my ($ok) = $self->{AllowedOutsideSubquery}->{$funcName}; return $ok if defined $ok; $XML::XQL::AllowedOutsideSubquery{$funcName}; } package XML::XQL::Operator; use fields qw{ Left Right Parent }; sub new { my ($class, %attr) = @_; my $self = bless \%attr, $class; $self->{Left}->setParent ($self) if defined $self->{Left}; $self->{Right}->setParent ($self) if defined $self->{Right}; $self; } sub dispose { my $self = shift; if (defined ($self->{Left})) { $self->{Left}->dispose; undef $self->{Left}; } if (defined ($self->{Right})) { $self->{Right}->dispose; undef $self->{Right}; } undef $self->{Parent}; } sub xql_check { my ($self, $inSubQuery, $inParam) = @_; $self->{Left}->xql_check ($inSubQuery, $inParam); $self->{Right}->xql_check ($inSubQuery, $inParam) if defined $self->{Right}; } sub xql_prepCache { my ($self) = @_; $self->{Left}->xql_prepCache; $self->{Right}->xql_prepCache if defined $self->{Right}; } sub xql_toDOM { my ($self, $doc) = @_; my $name = ref $self; $name =~ s/.*:://; my $elem = $doc->createElement ($name); if (defined $self->{Left}) { my $left = $doc->createElement ("left"); $elem->appendChild ($left); $left->appendChild ($self->{Left}->xql_toDOM ($doc)); } if (defined $self->{Right}) { my $right = $doc->createElement ("right"); $elem->appendChild ($right); $right->appendChild ($self->{Right}->xql_toDOM ($doc)); } $elem; } sub isConstant { 0; } # Overriden by Union and Path operators sub mustSort { 0; } sub setParent { $_[0]->{Parent} = $_[1]; } sub warning { my ($self, $msg) = @_; print STDERR "WARNING: $msg"; print STDERR " Context: " . $self->toContextString . "\n"; } sub root { my ($self) = @_; my $top = $self; while (defined ($top->{Parent})) { $top = $top->{Parent}; } $top; } sub query { $_[0]->root->{Query}; } sub toContextString { my ($self) = @_; $self->root->xql_contextString ($self); } sub debugString { my ($self) = @_; my $str = "[" . ref($self); while (my ($key, $val) = each %$self) { $str .= "$key=>" . XML::XQL::d($val); } $str . "]"; } sub verbose { my ($self, $str, $list) = @_; # print STDERR "$self - $str: " . XML::XQL::d($list) . "\n"; $list; } package XML::XQL::Root; # "/" at start of XQL expression use base 'XML::XQL::Operator'; # L -> L sub solve { my ($self, $context, $list) = @_; return [] if (@$list < 1); #?? what if first value is not a XML::XQL::Node? should we try the second one? [$list->[0]->xql_document]; } #?? add isOnce here? sub xql_check { } sub xql_prepCache { } sub xql_contextString { XML::XQL::delim ("/", @_); } package XML::XQL::Path; use base 'XML::XQL::Operator'; # L -> L use fields qw{ PathOp }; sub new { my ($class, %arg) = @_; my $self = bless \%arg, $class; $self->{Left} ||= new XML::XQL::Root; $self->{Left}->setParent ($self); $self->{Right}->setParent ($self); $self; } sub solve { my ($self, $context, $list) = @_; $list = $self->{Left}->solve ($context, $list); $self->verbose ("left", $list); return $list if @$list < 1; if ($self->{PathOp} eq '/') { $self->verbose ("result", $self->{Right}->solve ($context, $list)); } else # recurse "//" { my $new_list = []; my $n = @$list; NODE: for (my $i = 0; $i < $n; $i++) { my $node = $list->[$i]; # Node must be an Element or must be allowed to contain Elements # i.e. must be an Element or a Document # (DocumentFragment is not expected here) my $nodeType = $node->xql_nodeType; next NODE unless ($nodeType == 1 || $nodeType == 9); # Skip the node if one of its ancestors is part of the input $list # (and therefore already processed) my $parent = $node->xql_parent; while (defined $parent) { for (my $j = $i - 1; $j >= 0; $j--) { next NODE if ($parent == $list->[$j]); } $parent = $parent->xql_parent; } recurse ($node, $new_list); } my $results = $self->{Right}->solve ($context, $new_list); # Sort the result list unless the parent Operator will sort my $parent = $self->{Parent}; XML::XQL::sortDocOrder ($results) unless defined ($parent) and $parent->mustSort; $self->verbose ("result //", $results); } } sub mustSort { $_[0]->{PathOp} eq '//'; } sub recurse { my ($node, $list) = @_; push @$list, $node; for my $kid (@{$node->xql_element}) { recurse ($kid, $list); } } sub xql_contextString { my $self = shift; my $str = $self->{Left}->isa ('XML::XQL::Root') ? "" : $self->{Left}->xql_contextString (@_); XML::XQL::delim ($str . XML::XQL::bold($self->{PathOp}) . $self->{Right}->xql_contextString (@_), $self, @_); } sub xql_toDOM { my ($self, $doc) = @_; my $elem = $self->SUPER::xql_toDOM ($doc); $elem->setAttribute ("pathOp", $self->{PathOp}); $elem; } package XML::XQL::Sequence; # "elem;elem" or "elem;;elem" use base 'XML::XQL::Operator'; # L -> L use fields qw{ Oper }; # See "The Design of XQL" by Jonathan Robie # # for definition of Sequence operators. # Note that the "naive" implementation slows things down quite a bit here... sub solve { my ($self, $context, $list) = @_; my $left = $self->{Left}->solve ($context, $list); $self->verbose ("left", $left); return [] unless @$left; my $right = $self->{Right}->solve ($context, $list); $self->verbose ("right", $right); return [] unless @$right; my @result; if ($self->{Oper} eq ';') # immediately precedes { my %hleft; @hleft{@$left} = (); # initialize all values to undef my %pushed; for my $r (@$right) { # Find previous sibling that is not a text node that has only # whitespace that can be ignored (because xml:space=preserve) my $prev = $r->xql_prevNonWS; # $prev must be defined and must exist in $left next unless $prev and exists $hleft{$prev}; # Filter duplicates (no need to sort afterwards) push @result, $prev unless $pushed{$prev}++; push @result, $r unless $pushed{$r}++; } } else # oper eq ';;' (i.e. precedes) { my %pushed; for my $r (@$right) { for my $l (@$left) { # If left node precedes right node, add them if ($l->xql_sortKey lt $r->xql_sortKey) { # Filter duplicates push @result, $l unless $pushed{$l}++; push @result, $r unless $pushed{$r}++; } } #?? optimize - left & right are already sorted... # sort in document order XML::XQL::sortDocOrder (\@result) if @result; } } \@result; } sub xql_contextString { my $self = shift; XML::XQL::delim ($self->{Left}->xql_contextString (@_) . XML::XQL::bold($self->{Oper}) . $self->{Right}->xql_contextString (@_), $self, @_); } package XML::XQL::Current; # "." use base 'XML::XQL::Operator'; # L -> L sub xql_check { } sub xql_prepCache { } sub solve { my ($self, $context, $list) = @_; $list; } sub xql_contextString { XML::XQL::delim (".", @_); } package XML::XQL::Parent; # ".." use base 'XML::XQL::Operator'; sub xql_check { } sub xql_prepCache { } sub solve { my ($self, $context, $list) = @_; my @result = (); for my $node (@$list) { push @result, $node->xql_parent; } \@result; } sub xql_contextString { XML::XQL::delim ("..", @_); } package XML::XQL::Element; # "elem" use base 'XML::XQL::Operator'; # L -> L use fields qw{ Name NameSpace Expr }; sub new { my ($class, %args) = @_; if (not defined ($args{NameSpace})) { if ($args{Name} eq "*") { return bless \%args, 'XML::XQL::AllElements'; } else { return bless \%args, 'XML::XQL::SimpleElement'; } } $args{Expr} = XML::XQL::buildNameSpaceExpr ($args{NameSpace}, $args{Name}); bless \%args, $class; } sub xql_check { } sub xql_prepCache { } sub solve { my ($self, $context, $list) = @_; my @result = (); my $expr = $self->{Expr}; for my $node (@$list) { for my $kid (@{$node->xql_element}) { push @result, $kid if $kid->xql_nodeName =~ /$expr/; } } \@result; } sub xql_contextString { my $self = shift; my $name = $self->{Name}; my $space = $self->{NameSpace}; my $str = defined($space) ? "$space:$name" : $name; XML::XQL::delim ($str, $self, @_); } sub xql_toDOM { my ($self, $doc) = @_; my $elem = $self->SUPER::xql_toDOM ($doc); my $name = $self->{Name}; my $space = $self->{NameSpace}; my $str = defined($space) ? "$space:$name" : $name; $elem->setAttribute ("name", $str); $elem; } package XML::XQL::SimpleElement; # "elem" use base 'XML::XQL::Element'; # L -> L sub solve { my ($self, $context, $list) = @_; my @result = (); my $name = $self->{Name}; for my $node (@$list) { push @result, @{ $node->xql_element ($name) }; } \@result; } package XML::XQL::AllElements; # "*" use base 'XML::XQL::Element'; # L -> L sub solve { my ($self, $context, $list) = @_; my @result = (); for my $node (@$list) { push @result, @{$node->xql_element}; } \@result; } package XML::XQL::Attribute; # "@attr" use base 'XML::XQL::Operator'; # L -> L of Attributes use fields qw{ Name NameSpace Expr }; sub new { my ($class, %args) = @_; if (not defined ($args{NameSpace})) { if ($args{Name} eq "*") { return bless \%args, 'XML::XQL::AllAttr'; } else { return bless \%args, 'XML::XQL::SimpleAttr'; } } $args{Expr} = XML::XQL::buildNameSpaceExpr ($args{NameSpace}, $args{Name}); bless \%args, $class; } sub xql_check { } sub xql_prepCache { } sub solve { my ($self, $context, $list) = @_; my @result = (); my $expr = $self->{Expr}; for my $node (@$list) { for my $kid (@{$node->xql_attribute}) { push @result, $kid if $kid->xql_nodeName =~ /$expr/; } } } sub xql_contextString { my $self = shift; my $name = $self->{Name}; my $space = $self->{NameSpace}; my $str = defined($space) ? "\@$space:$name" : ('@' . $name); XML::XQL::delim ($str, $self, @_); } package XML::XQL::SimpleAttr; # "@attr" use base 'XML::XQL::Attribute'; # L -> L sub solve { my ($self, $context, $list) = @_; my @result = (); my $name = $self->{Name}; for my $node (@$list) { push @result, @{ $node->xql_attribute ($name) }; } \@result; } package XML::XQL::AllAttr; # "@*" use base 'XML::XQL::Attribute'; # L -> L sub solve { my ($self, $context, $list) = @_; my @result = (); for my $node (@$list) { push @result, @{$node->xql_attribute}; } \@result; } package XML::XQL::Subscript; # "[3, 5 $to$ 7, -1]" use base 'XML::XQL::Operator'; # L -> L use fields qw{ IndexList }; #?? optimize for simple subscripts sub solve { my ($self, $context, $inlist) = @_; my @result = (); for my $node (@$inlist) { my $list = $self->{Left}->solve ($context, [$node]); $self->verbose("Left", $list); my $n = int (@$list); next if ($n == 0); # build ordered index list my @indexFlags = (); $#indexFlags = $n - 1; my $index = $self->{IndexList}; my $len = @$index; #?? this is done a lot - optimize.... my $i = 0; while ($i < $len) { my $start = $index->[$i++]; $start += $n if ($start < 0); my $end = $index->[$i++]; $end += $n if ($end < 0); next unless $start <= $end && $end >=0 && $start < $n; $start = 0 if ($start < 0); $end = $n-1 if ($end >= $n); for my $j ($start .. $end) { $indexFlags[$j] = 1; } } for $i (0 .. $n-1) { push @result, $list->[$i] if $indexFlags[$i]; } } \@result; } sub xql_contextString { my $self = shift; my $index = $self->{IndexList}; my $str = XML::XQL::bold("["); for (my $i = 0; $i < @$index; $i++) { $str .= ", " if $i > 0; my $s = $index->[$i++]; my $e = $index->[$i]; $str = ($s == $e) ? $s : "$s \$to\$ $e"; } $str .= XML::XQL::bold("]"); XML::XQL::delim ($self->{Left}->xql_contextString (@_) . $str, $self, @_); } sub xql_toDOM { my ($self, $doc) = @_; my $elem = $self->SUPER::xql_toDOM ($doc); my $index = $self->{IndexList}; my $str = ""; for (my $i = 0; $i < @$index; $i++) { $str .= ", " if $i > 0; my $s = $index->[$i++]; my $e = $index->[$i]; $str .= ($s == $e) ? $s : "$s \$to\$ $e"; } my $ie = $doc->createElement ("index"); $ie->setAttribute ("list", $str); $elem->appendChild ($ie); $elem; } package XML::XQL::Union; # "book $union$ magazine", also "|" use base 'XML::XQL::Operator'; # L x L -> L sub solve { my ($self, $context, $list) = @_; my $left = XML::XQL::toList ($self->{Left}->solve ($context, $list)); my $right = XML::XQL::toList ($self->{Right}->solve ($context, $list)); return $right if (@$left < 1); return $left if (@$right < 1); my @result = @$left; for my $node (@$right) { push @result, $node unless XML::XQL::listContains ($left, $node); } my $parent = $self->{Parent}; # Don't sort if parent is a Union or //, because the parent will do the sort unless (defined $parent and $parent->mustSort) { XML::XQL::sortDocOrder (\@result) } # $self->verbose ("Union result", \@result); \@result; } sub mustSort { 1; } sub xql_contextString { my $self = shift; XML::XQL::delim ($self->{Left}->xql_contextString (@_) . XML::XQL::bold (" \$union\$ ") . $self->{Right}->xql_contextString (@_), $self, @_); } package XML::XQL::Intersect; # "book $intersect$ magazine" use base 'XML::XQL::Operator'; # L x L -> L sub solve { my ($self, $context, $list) = @_; my $left = XML::XQL::toList ($self->{Left}->solve ($context, $list)); return [] if @$left < 1; my $right = XML::XQL::toList ($self->{Right}->solve ($context, $list)); return [] if @$right < 1; # Assumption: $left and $right don't have duplicates themselves my @result = (); for my $node (@$left) { #? reimplement with hash - faster! push @result, $node if XML::XQL::listContains ($right, $node); } \@result; } sub xql_contextString { my $self = shift; XML::XQL::delim ($self->{Left}->xql_contextString (@_) . XML::XQL::bold (" \$intersect\$ ") . $self->{Right}->xql_contextString (@_), $self, @_); } package XML::XQL::Filter; # "elem[expr]" use base 'XML::XQL::Operator'; # L -> L sub solve { my ($self, $context, $inlist) = @_; my @result = (); for my $node (@$inlist) { my $list = $self->{Left}->solve ($context, [$node]); next if @$list == 0; my $subQuery = $self->{Right}; $context = [0, scalar (@$list)]; for my $node (@$list) { #?? optimize? only need the first one to succeed my $r = $subQuery->solve ($context, [ $node ]); push @result, $node if XML::XQL::toBoolean ($r); $context->[0]++; # increase the index for the index() method } } \@result; } sub xql_check { my ($self, $inSubQuery, $inParam) = @_; $self->{Left}->xql_check ($inSubQuery, $inParam); $self->{Right}->xql_check (1, $inParam); } sub xql_contextString { my $self = shift; XML::XQL::delim ($self->{Left}->xql_contextString (@_) . XML::XQL::bold ("[") . $self->{Right}->xql_contextString (@_) . XML::XQL::bold ("]"), $self, @_); } package XML::XQL::BooleanOp; use base 'XML::XQL::Operator'; package XML::XQL::Or; use base 'XML::XQL::BooleanOp'; sub solve { my ($self, $context, $list) = @_; my $left = $self->{Left}->solve ($context, $list); return $XML::XQL::Boolean::TRUE if XML::XQL::toBoolean ($left); return $self->{Right}->solve ($context, $list); } sub xql_contextString { my $self = shift; XML::XQL::delim ($self->{Left}->xql_contextString (@_) . XML::XQL::bold (" \$or\$ ") . $self->{Right}->xql_contextString (@_), $self, @_); } package XML::XQL::And; use base 'XML::XQL::BooleanOp'; sub solve { my ($self, $context, $list) = @_; my $left = $self->{Left}->solve ($context, $list); return $XML::XQL::Boolean::FALSE unless XML::XQL::toBoolean ($left); return $self->{Right}->solve ($context, $list); } sub xql_contextString { my $self = shift; XML::XQL::delim ($self->{Left}->xql_contextString (@_) . XML::XQL::bold (" \$and\$ ") . $self->{Right}->xql_contextString (@_), $self, @_); } package XML::XQL::Not; use base 'XML::XQL::BooleanOp'; sub solve { my ($self, $context, $list) = @_; my $left = $self->{Left}->solve ($context, $list); return XML::XQL::toBoolean ($left) ? $XML::XQL::Boolean::FALSE : $XML::XQL::Boolean::TRUE; } sub xql_contextString { my $self = shift; XML::XQL::delim (XML::XQL::bold ("\$not\$ ") . $self->{Left}->xql_contextString (@_), $self, @_); } package XML::XQL::Compare; use base 'XML::XQL::Operator'; use fields qw{ Func All }; use Carp; sub solve { my ($self, $context, $list) = @_; my $type; my $cmpFunc = $self->{Func}; my $left = $self->verbose ("left", XML::XQL::toList ($self->{Left}->solve ($context, $list))); return [] if @$left < 1; my $right; eval { $right = $self->verbose ("right", XML::XQL::prepareRvalue ($self->{Right}->solve ($context, $list))); }; return [] if XML::XQL::exception ($@); if ($self->{All}) { for my $node (@$left) { eval { # Stop if any of the comparisons fails return [] unless &$cmpFunc ($node, $right); }; return [] if XML::XQL::exception ($@); } return $left; } else # $any$ { my @result = (); for my $node (@$left) { eval { push (@result, $node) if &$cmpFunc ($node, $right); }; return [] if XML::XQL::exception ($@); } return \@result; } } sub xql_contextString { my $self = shift; my $all = $self->{All} ? "\$all\$ " : ""; XML::XQL::delim ($all . $self->{Left}->xql_contextString (@_) . " " . XML::XQL::bold ($self->{Oper}) . " " . $self->{Right}->xql_contextString (@_), $self, @_); } package XML::XQL::Func; use Carp; sub count { my ($context, $list, $expr) = @_; my $cnt; if (defined $expr) { $list = XML::XQL::toList ($expr->solve ($context, $list)); $cnt = @$list; } else { $cnt = $context->[1]; } #?? ref node? new XML::XQL::Number ($cnt); } sub id { my ($context, $list, $query) = @_; return [] if @$list == 0; my $id = XML::XQL::prepareRvalue ($query->solve ($context, $list)); #?? check result? #?? if [0] is not a Node, I should probably try the next one my $doc = $list->[0]->xql_document; _findId ($doc->xql_element->[0], $id); } sub _findId # static method { my ($elem, $id) = @_; my $attr = $elem->xql_attribute ("id"); return [$elem] if (@$attr == 1 && $attr->[0]->xql_nodeName eq $id); for my $kid (@{$elem->xql_element}) { $attr = _findId ($kid); return $attr if @$attr; } return []; } sub end { my ($context, $list) = @_; return [] if @$list == 0; new XML::XQL::Boolean ($context->[0] == $context->[1] - 1); } sub xql_index { my ($context, $list) = @_; # print "index: " . XML::XQL::d($context) . "\n"; #?? wrong! return [] if @$list == 0; new XML::XQL::Number ($context->[0]); } sub ancestor { my ($context, $list, $query) = @_; return [] if @$list == 0; my @anc = (); #?? fix for @$list > 1 my $parent = $list->[0]->xql_parent; while (defined $parent) { # keep list of ancestors so far unshift @anc, $parent; # solve the query for the ancestor my $result = $query->solve ($context, [$parent]); for my $node (@{$result}) { for my $anc (@anc) { return [$node] if $node == $anc; } } $parent = $parent->xql_parent; } return []; } sub node { my ($context, $list) = @_; return [] if @$list == 0; return $list->[0]->xql_node if @$list == 1; my @result; for my $node (@$list) { push @result, @{ $node->xql_node }; } XML::XQL::sortDocOrder (\@result); } sub _nodesByType { my ($list, $type) = @_; return [] if @$list == 0; my @result; for my $node (@$list) { for my $kid (@{ $node->xql_node }) { push @result, $kid if $kid->xql_nodeType == $type; } } @$list > 1 ? XML::XQL::sortDocOrder (\@result) : \@result; } sub pi { my ($context, $list, $pi_name) = @_; if (defined $pi_name) { return [] if @$list == 0; $pi_name = $pi_name->solve ($context, $list)->xql_toString; my @result; for my $node (@$list) { for my $kid (@{ $node->xql_node }) { push @result, $kid if $kid->xql_nodeType == 7 && $kid->getTarget eq $pi_name; } } return @$list > 1 ? XML::XQL::sortDocOrder (\@result) : \@result; } return _nodesByType ($_[1], 7); } sub comment { _nodesByType ($_[1], 8); } sub textNode { _nodesByType ($_[1], 3); } sub nodeName { my ($context, $list) = @_; return [] if @$list == 0; my @result; for my $node (@$list) { push @result, new XML::XQL::Text ($node->xql_nodeName, $node); } \@result; } sub namespace { my ($context, $list) = @_; return [] if @$list == 0; my @result; for my $node (@$list) { my $namespace = $node->xql_namespace; next unless defined $namespace; push @result, new XML::XQL::Text ($namespace, $node); } \@result; } sub prefix { my ($context, $list) = @_; return [] if @$list == 0; my @result; for my $node (@$list) { my $prefix = $node->xql_prefix; next unless defined $prefix; push @result, new XML::XQL::Text ($prefix, $node); } \@result; } sub baseName { my ($context, $list) = @_; return [] if @$list == 0; my @result; for my $node (@$list) { my $basename = $node->xql_baseName; next unless defined $basename; push @result, new XML::XQL::Text ($basename, $node); } \@result; } sub nodeType { my ($context, $list) = @_; return [] if @$list == 0; my @result; for my $node (@$list) { push @result, new XML::XQL::Number ($node->xql_nodeType, $node); } \@result; } sub nodeTypeString { my ($context, $list) = @_; return [] if @$list == 0; my @result; for my $node (@$list) { push @result, new XML::XQL::Text ($node->xql_nodeTypeString, $node); } @result; } sub value { my ($context, $list) = @_; return [] if @$list == 0; my @result; for my $node (@$list) { push @result, $node->xql_value; # value always returns an object } \@result; } sub text { my ($context, $list, $recurse) = @_; return [] if @$list == 0; if (defined $recurse) { $recurse = $recurse->solve ($context, $list)->xql_toString; } else { $recurse = 1; # default } my @result; for my $node (@$list) { my $text = $node->xql_text ($recurse); next unless defined $text; push @result, new XML::XQL::Text ($text, $node); } \@result; } sub rawText { my ($context, $list, $recurse) = @_; return [] if @$list == 0; if (defined $recurse) { $recurse = $recurse->solve ($context, $list)->xql_toString; } else { $recurse = 1; # default } my @result; for my $node (@$list) { my $text = $node->xql_rawText ($recurse); next unless defined $text; push @result, new XML::XQL::Text ($text, $node); } \@result; } sub true { return $XML::XQL::Boolean::TRUE; } sub false { return $XML::XQL::Boolean::FALSE; } #sub date() is in XQL::XML::Date sub element { my ($context, $list, $text) = @_; return [] if @$list == 0; my @result; if (defined $text) { $text = XML::XQL::prepareRvalue ($text->solve ($context, $list))->xql_toString; for my $node (@$list) { push @result, @{$node->xql_element ($text)}; } } else { for my $node (@$list) { push @result, @{$node->xql_element}; } } @$list > 1 ? XML::XQL::sortDocOrder (\@result) : \@result; } sub attribute { my ($context, $list, $text) = @_; return [] if @$list == 0; my @result; if (defined $text) { $text = XML::XQL::prepareRvalue ($text->solve ($context, $list))->xql_toString; for my $node (@$list) { push @result, @{ $node->xql_attribute ($text) }; } } else { for my $node (@$list) { push @result, @{ $node->xql_attribute }; } } \@result; } package XML::XQL::Bang; use base 'XML::XQL::Operator'; sub solve { my ($self, $context, $list) = @_; $list = $self->{Left}->solve ($context, $list); $self->{Right}->solve ($context, $list); } sub xql_contextString { my $self = shift; XML::XQL::delim ($self->{Left}->xql_contextString (@_) . XML::XQL::bold ("!") . $self->{Right}->xql_contextString (@_), $self, @_); } package XML::XQL::Invocation; use base 'XML::XQL::Operator'; use fields qw{ Args Name Type Once ConstVal }; use Carp; sub new { my ($class, %args) = @_; my $self = bless \%args, $class; for my $par (@{$self->{Args}}) { $par->setParent ($self); } $self; } sub dispose { my $self = shift; for (@{ $self->{Args} }) { $_->dispose; } undef $self->{Args}; undef $self->{Parent}; } sub isConstant { my ($self) = @_; # An Invocation is constant, if all it's arguments are constant # and it's a "constant" function my $name = $self->{Name}; my $cf = $self->query->{ConstFunc}; my $const = exists ($cf->{$name}) ? $cf->{name} : $XML::XQL::ConstFunc{$name}; return 0 unless $const; for my $par (@{$self->{Args}}) { return 0 unless $par->isConstant; } 1; } sub xql_check { my ($self, $inSubQuery, $inParam) = @_; # Syntactic Constraint 7: # In a node query this function or method is only valid inside an instance # of Subquery, unless it appears within an instance of Param. # Functions and methods are valid anywhere in a full query. my $query; if (not ($inSubQuery or $inParam) and ($query = $self->query)->isNodeQuery) { unless ($query->isAllowedOutsideSubquery ($self->{Name})) { XML::XQL::parseError $self->{Type} . " " . $self->{Name} . " is only allowed inside a Subquery or Param for 'Node Queries'." . " Context: " . $self->toContextString; } } for my $par (@{$self->{Args}}) { $par->xql_check ($inSubQuery, 1); # these are Params } # once() should only be evaluated once per query # "constant" functions should only be evaluated once *ever* $self->{Once} = $self->isOnce || $self->isConstant; } sub xql_prepCache { my ($self) = @_; # once() should only be evaluated once per query # "constant" functions should only be evaluated once *ever* delete $self->{ConstVal} if $self->isOnce; for my $par (@{$self->{Args}}) { $par->xql_prepCache; } } sub isOnce { $_[0]->{Name} eq "once"; } sub isMethod { $_[0]->{Type} eq "method"; } sub solve { my ($self, $context, $list) = @_; # Use the cached value if it's a "constant" function return $self->{ConstVal} if (exists $self->{ConstVal}); my $func = $self->{Func}; my $result; eval { $result = &$func ($context, $list, @{$self->{Args}}); $self->{ConstVal} = $result if $self->{Once}; }; if ($@) { #?? or croak $self->warning ("invocation of '" . $self->{Name} . "' failed:\n\t$@"); $self->{ConstVal} = [] if $self->{Once}; return []; } $result; } sub xql_contextString { my $self = shift; my $str = XML::XQL::bold ($self->{Name}) . "("; for (my $i = 0; $i < @{$self->{Args}}; $i++) { $str .= ", " if $i > 0; $str .= $self->{Args}->[$i]->xql_contextString (@_); } $str .= ")"; XML::XQL::delim ($str, $self, @_); } # Base class shared by Node and PrimitiveType package XML::XQL::PrimitiveTypeBase; sub dispose { } sub xql_check { } sub xql_prepCache { } sub xql_prevSibling { undef; } # This method returns an integer that determines how values should be casted # for comparisons. If the left value (LHS) has a higher xql_primType, the # right value (RHS) is cast to the type of the LHS (otherwise, the LHS is casted # to the type of the LHS) # # Values for certain types: # Node 0 (always cast a node to a Text string first) # Text 1 # Number 2 # Boolean 3 # Date 4 (other classes automatically use 4 by default) sub xql_primType { 4; # default for all classes other then Node, Text, Number, Boolean } sub xql_toBoolean { 1; # it is true if it exists } sub xql_namespace { undef; } sub xql_baseName { undef; } sub xql_prefix { undef; } sub xql_sortKey { my $src = $_[0]->xql_sourceNode; $src ? $src->xql_sortKey : $XML::XQL::LAST_SORT_KEY; } sub xql_toDOM { my ($self, $doc) = @_; my $name = ref $self; $name =~ s/.*:://; my $elem = $doc->createElement ($name); $elem->setAttribute ("value", $self->xql_toString); $elem; } package XML::XQL::PrimitiveType; use vars qw( @ISA ); @ISA = qw( XML::XQL::PrimitiveTypeBase ); sub new { my ($class, $val, $srcNode) = @_; bless [$val, $srcNode], $class; } sub isConstant { 1; } sub setParent { # not defined } sub solve { $_[0]; # evaluates to itself } # # Derived classes should not override this method. # Override xql_toString instead. # sub xql_contextString { my $self = shift; XML::XQL::delim ($self->xql_toString, $self, @_); } # # Return the value of the Object as a primitive Perl value, i.e. an integer, # a float, or a string. # sub xql_toString { $_[0]->[0]; } sub xql_sourceNode { $_[0]->[1]; } sub xql_setSourceNode { $_[0]->[1] = $_[1]; } sub xql_setValue { # This could potentially change the value of a constant in the XQL # query expression. $_[0]->[0] = $_[1]; } sub xql_nodeType { 0; # it's not a Node } sub xql_compare { # Temporarily switch off $WARNING flag, to disable messages a la: # Argument "1993-02-14" isn't numeric in ncmp local $^W = 0; $_[0]->[0] <=> $_[1]->xql_toString; } sub xql_eq { my $self = shift; $self->xql_compare (@_) == 0; } sub xql_ne { my $self = shift; $self->xql_compare (@_) != 0; } sub xql_lt { my $self = shift; $self->xql_compare (@_) < 0; } sub xql_le { my $self = shift; $self->xql_compare (@_) <= 0; } sub xql_gt { my $self = shift; $self->xql_compare (@_) > 0; } sub xql_ge { my $self = shift; $self->xql_compare (@_) >= 0; } package XML::XQL::Boolean; use vars qw( @ISA @EXPORT $TRUE $FALSE ); use Carp; @ISA = qw( XML::XQL::PrimitiveType ); @EXPORT = qw( $TRUE $FALSE ); $TRUE = new XML::XQL::Boolean (1); $FALSE = new XML::XQL::Boolean (0); sub xql_primType { 3; } sub xql_toBoolean { $_[0]->[0]; # evaluate it to its value } sub xql_negate { #?? do we need to keep track of a source node here? $_[0]->[0] ? $FALSE : $TRUE; } sub xql_compare { #?? how do we convert string to boolean value $_[0]->[0] <=> ($_[1]->xql_toString ? 1 : 0); } sub xql_lt { badComparisonError (@_); } sub xql_gt { badComparisonError (@_); } sub xql_le { badComparisonError (@_); } sub xql_ge { badComparisonError (@_); } sub badComparisonError { croak 'comparison operator (other than =, !=, $ieq$, $ine$) not defined for type Boolean'; } package XML::XQL::Number; use vars qw( @ISA ); @ISA = qw( XML::XQL::PrimitiveType ); #use overload # 'fallback' => 1, # use default operators, if not specified # '""' => \&debug; sub debug { "Number[" . $_[0]->[0] . "]"; } sub xql_primType { 2; } package XML::XQL::Text; use vars qw( @ISA ); @ISA = qw( XML::XQL::PrimitiveType ); #use overload # 'fallback' => 1, # use default operators, if not specified # '""' => \&debug; sub debug { "Text[" . $_[0]->[0] . "]"; } sub xql_primType { 1; } sub xql_compare { my ($self, $other, $ignoreCase) = @_; if ($ignoreCase) { my $lhs = $self->[0]; my $rhs = $other->xql_toString; "\U$lhs" cmp "\U$rhs"; } else { $self->[0] cmp $other->xql_toString; } } # Declare package XML::XQL::Node so that XML implementations can say # that their nodes derive from it: # # This worked for me when I added XQL support for XML::DOM: # # BEGIN # { # push @XML::DOM::Node::ISA, 'XML::XQL::Node'; # } # package XML::XQL::Node; use vars qw( @ISA ); @ISA = qw( XML::XQL::PrimitiveTypeBase ); use Carp; sub xql_primType { 0; } sub xql_toBoolean { 1; # it is true if it exists } sub xql_attribute { []; } sub xql_sourceNode { $_[0]; } # Default implementation - override this for speed sub xql_element { my ($node, $elem) = @_; my @list = (); if (defined $elem) { for my $kid (@{$_[0]->xql_node}) { # 1: element push @list, $kid if $kid->xql_nodeType == 1 && $kid->xql_nodeName eq $elem; } } else { for my $kid (@{$_[0]->xql_node}) { push @list, $kid if $kid->xql_nodeType == 1; # 1: element } } \@list; } sub xql_text { undef; } sub xql_rawText { undef; } sub xql_rawTextBlocks { undef; } sub xql_value { new XML::XQL::Text ($_[0]->xql_text ($_[1]), $_[0]); } # Convert xql_value to Perl string (or undef if xql_value is undefined) sub xql_toString { my $val = $_[0]->xql_value; return undef if XML::XQL::isEmptyList ($val); $val->xql_toString; } sub xql_setValue { # Not implemented for most node types } sub xql_data { ""; } sub xql_nodeType { 0; } sub xql_nodeName { []; } # Java code from "XML:: Namespaces in 20 lines" by James Clark: # see: http://www.oasis-open.org/cover/clarkNS-980804.html # # String expandName(String name, Element element, boolean isAttribute) { # // The index of the colon character in the name. # int colonIndex = name.indexOf(':'); # // The name of the attribute that declares the namespace prefix. # String declAttName; # if (colonIndex == -1) { # // Default namespace applies only to element type names. # if (isAttribute) # return name; # declAttName = "xmlns"; # } # else { # String prefix = name.substring(0, colonIndex); # // "xml:" is special # if (prefix.equals("xml")) # return name; # declAttName = "xmlns:" + prefix; # } # for (; element != null; element = element.getParent()) { # String ns = element.getAttributeValue(declAttName); # if (ns != null) { # // Handle special meaning of xmlns="" # if (ns.length() == 0 && colonIndex == -1) # return name; # return ns + '+' + name.substring(colonIndex + 1); # } # } # return null; # } # From "Namespaces in XML" # at http://www.w3.org/TR/1998/WD-xml-names-19980916 # # The prefix xml is by definition bound to the namespace name # urn:Connolly:input:required. The prefix xmlns is used only for # namespace bindings and is not itself bound to any namespace name. my $DEFAULT_NAMESPACE = undef; my $XML_NAMESPACE = "urn:Connolly:input:required"; #?? default namespace sub xql_namespace { my ($self) = @_; my $nodeType = $self->xql_nodeType; my $element = $self; if ($nodeType == 2) # 2: Attr { $element = $self->xql_parent; } elsif ($nodeType != 1) # 1: Element { return undef; } my $name = $self->xql_nodeName; my $declAttName; if ($name =~ /([^:]+):([^:]+)/) { my ($prefix, $basename) = ($1, $2); # "xml:" is special return $XML_NAMESPACE if $prefix eq "xml"; $declAttName = "xmlns:$prefix"; } else { # Default namespace applies only to element type names. return $DEFAULT_NAMESPACE if $nodeType == 2; # 2: Attr #?? default namespace? $declAttName = "xmlns"; } do { my $ns = $element->xql_attribute ($declAttName); next unless defined $ns; return $ns->xql_rawText; $element = $element->xql_parent; } while (defined ($element) and $element->xql_nodeType == 1); # namespace not found undef; } sub xql_basename { my ($self) = @_; my $nodeType = $self->xql_nodeType; return undef unless $nodeType == 1 || $nodeType == 2; my $name = $self->xql_nodeName; $name =~ s/^[^:]://; # strip prefix $name; } sub xql_prefix { my ($self) = @_; my $nodeType = $self->xql_nodeType; return undef unless $nodeType == 1 || $nodeType == 2; $self->xql_nodeName =~ /^([^:]+):/; $1; } # Used by ancestor() sub xql_parent { undef; } my @NodeTypeString = ( "", "element", "attribute", "text", "", "", "", "processing_instruction", "comment", "document" ); sub xql_nodeTypeString { my $i = $_[0]->xql_nodeType; return $NodeTypeString[$i] if ($i >= 1 && $i <= 3 || $i >= 7 && $i <= 9); #?? what should this return? ""; } if (not $XML::XQL::Restricted) { require XML::XQL::Plus; } # All nodes should implement: #?? this section must be updated!! # - xql_document # - xql_node: return an unblessed list reference with childNodes (not # attributes) # - xql_nodeType (default implementation for XML::XQL::Node returns 0): # Element: 1 # Element Attribute: 2 # Markup-Delimited Region of Text (Text and CDATASection): 3 # Processing Instruction: 7 # Comment: 8 # Document (Entity): 9 # - xql_text # - xql_value (default implementation is xql_text) # - xql_parent: return parent node or undef (Document, DocumentFragment) # # Element should define/override the following: # - xql_nodeName: return the element name # - xql_attribute("attributeName"): return an unblessed reference to a list # with the attribute, or [] if no such attribute # - xql_attribute(): return an unblessed reference to a list with # all attribute nodes # - xql_baseName, xql_prefix # # Attribute: # - xql_nodeName: return the attribute name # - xql_baseName, xql_prefix # # EntityReference: # - xql_data: return expanded text value # # Text, CDATASection: # - xql_data: return expanded text value # # -xql_element could be overriden to speed up performance # 1; __END__ =head1 NAME XML::XQL - A perl module for querying XML tree structures with XQL =head1 SYNOPSIS use XML::XQL; use XML::XQL::DOM; $parser = new XML::DOM::Parser; $doc = $parser->parsefile ("file.xml"); # Return all elements with tagName='title' under the root element 'book' $query = new XML::XQL::Query (Expr => "book/title"); @result = $query->solve ($doc); $query->dispose; # Avoid memory leaks - Remove circular references # Or (to save some typing) @result = XML::XQL::solve ("book/title", $doc); # Or (to save even more typing) @result = $doc->xql ("book/title"); =head1 DESCRIPTION The XML::XQL module implements the XQL (XML Query Language) proposal submitted to the XSL Working Group in September 1998. The spec can be found at: L Most of the contents related to the XQL syntax can also be found in the L that comes with this distribution. Note that XQL is not the same as XML-QL! The current implementation only works with the L module, but once the design is stable and the major bugs are flushed out, other extensions might follow, e.g. for XML::Grove. XQL was designed to be extensible and this implementation tries to stick to that. Users can add their own functions, methods, comparison operators and data types. Plugging in a new XML tree structure (like XML::Grove) should be a piece of cake. To use the XQL module, either use XML::XQL; or use XML::XQL::Strict; The Strict module only provides the core XQL functionality as found in the XQL spec. By default (i.e. by using XML::XQL) you get 'XQL+', which has some additional features. See the section L for the differences. This module is still in development. See the To-do list in XQL.pm for what still needs to be done. Any suggestions are welcome, the sooner these implementation issues are resolved, the faster we can all use this module. If you find a bug, you would do me great favor by sending it to me in the form of a test case. See the file t/xql_template.t that comes with this distribution. If you have written a cool comparison operator, function, method or XQL data type that you would like to share, send it to tjmather@tjmather.com and I will add it to this module. =head1 XML::XQL global functions =over 4 =item solve (QUERY_STRING, INPUT_LIST...) @result = XML::XQL::solve ("doc//book", $doc); This is provided as a shortcut for: $query = new XML::XQL::Query (Expr => "doc//book"); @result = $query->solve ($doc); $query->dispose; Note that with L, you can also write (see L for details): @result = $doc->xql ("doc//book"); =item setDocParser (PARSER) Sets the XML::DOM::Parser that is used by the new XQL+ document() method. By default it uses an XML::DOM::Parser that was created without any arguments, i.e. $PARSER = new XML::DOM::Parser; =item defineFunction (NAME, FUNCREF, ARGCOUNT [, ALLOWED_OUTSIDE [, CONST, [QUERY_ARG]]]) Defines the XQL function (at the global level, i.e. for all newly created queries) with the specified NAME. The ARGCOUNT parameter can either be a single number or a reference to a list with numbers. A single number expands to [ARGCOUNT, ARGCOUNT]. The list contains pairs of numbers, indicating the number of arguments that the function allows. The value -1 means infinity. E.g. [2, 5, 7, 9, 12, -1] means that the function can have 2, 3, 4, 5, 7, 8, 9, 12 or more arguments. The number of arguments is checked when parsing the XQL query string. The second parameter must be a reference to a Perl function or an anonymous sub. E.g. '\&my_func' or 'sub { ... code ... }' If ALLOWED_OUTSIDE (default is 0) is set to 1, the function or method may also be used outside subqueries in I. (See NodeQuery parameter in Query constructor) If CONST (default is 0) is set to 1, the function is considered to be "constant". See L for details. If QUERY_ARG (default is 0) is not -1, the argument with that index is considered to be a 'query parameter'. If the query parameter is a subquery, that returns multiple values, the result list of the function invocation will contain one result value for each value of the subquery. E.g. 'length(book/author)' will return a list of Numbers, denoting the string lengths of all the author elements returned by 'book/author'. Note that only methods (not functions) may appear after a Bang "!" operator. This is checked when parsing the XQL query string. See also: defineMethod =item generateFunction (NAME, FUNCNAME, RETURN_TYPE [, ARGCOUNT [, ALLOWED_OUTSIDE [, CONST [, QUERY_ARG]]]]) Generates and defines an XQL function wrapper for the Perl function with the name FUNCNAME. The function name will be NAME in XQL query expressions. The return type should be one of the builtin XQL Data Types or a class derived from XML::XQL::PrimitiveType (see L.) See defineFunction for the meaning of ARGCOUNT, ALLOWED_OUTSIDE, CONST and QUERY_ARG. Function values are always converted to Perl strings with xql_toString before they are passed to the Perl function implementation. The function return value is cast to an object of type RETURN_TYPE, or to the empty list [] if the result is undef. It uses expandType to expand XQL primitive type names. If RETURN_TYPE is "*", it returns the function result as is, unless the function result is undef, in which case it returns []. =item defineMethod (NAME, FUNCREF, ARGCOUNT [, ALLOWED_OUTSIDE]) Defines the XQL method (at the global level, i.e. for all newly created queries) with the specified NAME. The ARGCOUNT parameter can either be a single number or a reference to a list with numbers. A single number expands to [ARGCOUNT, ARGCOUNT]. The list contains pairs of numbers, indicating the number of arguments that the method allows. The value -1 means infinity. E.g. [2, 5, 7, 9, 12, -1] means that the method can have 2, 3, 4, 5, 7, 8, 9, 12 or more arguments. The number of arguments is checked when parsing the XQL query string. The second parameter must be a reference to a Perl function or an anonymous sub. E.g. '\&my_func' or 'sub { ... code ... }' If ALLOWED_OUTSIDE (default is 0) is set to 1, the function or method may also be used outside subqueries in I. (See NodeQuery parameter in Query constructor) Note that only methods (not functions) may appear after a Bang "!" operator. This is checked when parsing the XQL query string. See also: defineFunction =item defineComparisonOperators (NAME => FUNCREF [, NAME => FUNCREF]*) Defines XQL comparison operators at the global level. The FUNCREF parameters must be a references to a Perl function or an anonymous sub. E.g. '\&my_func' or 'sub { ... code ... }' E.g. define the operators $my_op$ and $my_op2$: defineComparisonOperators ('my_op' => \&my_op, 'my_op2' => sub { ... insert code here ... }); =item defineElementValueConvertor (TAG_NAME, FUNCREF) Defines that the result of the value() call for Elements with the specified TAG_NAME uses the specified function. The function will receive two parameters. The second one is the TAG_NAME of the Element node and the first parameter is the Element node itself. FUNCREF should be a reference to a Perl function, e.g. \&my_sub, or an anonymous sub. E.g. to define that all Elements with tag name 'date-of-birth' should return XML::XQL::Date objects: defineElementValueConvertor ('date-of-birth', sub { my $elem = shift; # Always pass in the node as the second parameter. This is # the reference node for the object, which is used when # sorting values in document order. new XML::XQL::Date ($elem->xql_text, $elem); }); These convertors can only be specified at a global level, not on a per query basis. To undefine a convertor, simply pass a FUNCREF of undef. =item defineAttrValueConvertor (ELEM_TAG_NAME, ATTR_NAME, FUNCREF) Defines that the result of the value() call for Attributes with the specified ATTR_NAME and a parent Element with the specified ELEM_TAG_NAME uses the specified function. An ELEM_TAG_NAME of "*" will match regardless of the tag name of the parent Element. The function will receive 3 parameters. The third one is the tag name of the parent Element (even if ELEM_TAG_NAME was "*"), the second is the ATTR_NAME and the first is the Attribute node itself. FUNCREF should be a reference to a Perl function, e.g. \&my_sub, or an anonymous sub. These convertors can only be specified at a global level, not on a per query basis. To undefine a convertor, simply pass a FUNCREF of undef. =item defineTokenQ (Q) Defines the token for the q// string delimiters at a global level. The default value for XQL+ is 'q', for XML::XQL::Strict it is undef. A value of undef will deactivate this feature. =item defineTokenQQ (QQ) Defines the token for the qq// string delimiters at a global level. The default value for XQL+ is 'qq', for XML::XQL::Strict it is undef. A value of undef will deactivate this feature. =item expandType (TYPE) Used internally to expand type names of XQL primitive types. E.g. it expands "Number" to "XML::XQL::Number" and is not case-sensitive, so "number" and "NuMbEr" will both expand correctly. =item defineExpandedTypes (ALIAS, FULL_NAME [, ...]) For each pair of arguments it allows the class name FULL_NAME to be abbreviated with ALIAS. The definitions are used by expandType(). (ALIAS is always converted to lowercase internally, because expandType is case-insensitive.) Overriding the ALIAS for "date", also affects the object type returned by the date() function. =item setErrorContextDelimiters (START, END, BOLD_ON, BOLD_OFF) Sets the delimiters used when printing error messages during query evaluation. The default delimiters on Unix are `tput smul` (underline on) and `tput rmal` (underline off). On other systems (that don't have tput), the delimiters are ">>" and "<<" resp. When printing the error message, the subexpression that caused the error will be enclosed by the delimiters, i.e. underlined on Unix. For certain subexpressions the significant keyword, e.g. "$and$" is enclosed in the bold delimiters BOLD_ON (default: `tput bold` on Unix, "" elsewhere) and BOLD_OFF (default: (`tput rmul` . `tput smul`) on Unix, "" elsewhere, see $BoldOff in XML::XQL::XQL.pm for details.) =item isEmptyList (VAR) Returns 1 if VAR is [], else 0. Can be used in user defined functions. =back =head1 Additional Features in XQL+ =over 4 =item Parent operator '..' The '..' operator returns the parent of the current node, where '.' would return the current node. This is not part of any XQL standard, because you would normally use return operators, which are not implemented here. =item Sequence operators ';' and ';;' The sequence operators ';' (precedes) and ';;' (immediately precedes) are not in the XQL spec, but are described in 'The Design of XQL' by Jonathan Robie who is one of the designers of XQL. It can be found at L See also the XQL Tutorial for a description of what they mean. =item q// and qq// String Tokens String tokens a la q// and qq// are allowed. q// evaluates like Perl's single quotes and qq// like Perl's double quotes. Note that the default XQL strings do not allow escaping etc., so it's not possible to define a string with both single and double quotes. If 'q' and 'qq' are not to your liking, you may redefine them to something else or undefine them altogether, by assigning undef to them. E.g: # at a global level - shared by all queries (that don't (re)define 'q') XML::XQL::defineTokenQ ('k'); XML::XQL::defineTokenQQ (undef); # at a query level - only defined for this query $query = new XML::XQL::Query (Expr => "book/title", q => 'k', qq => undef); From now on k// works like q// did and qq// doesn't work at all anymore. =item Query strings can have embedded Comments For example: $queryExpr = "book/title # this comment is inside the query string [. = 'Moby Dick']"; # this comment is outside =item Optional dollar delimiters and case-insensitive XQL keywords The following XQL keywords are case-insensitive and the dollar sign delimiters may be omitted: $and$, $or$, $not$, $union$, $intersect$, $to$, $any$, $all$, $eq$, $ne$, $lt$, $gt$, $ge$, $le$, $ieq$, $ine$, $ilt$, $igt$, $ige$, $ile$. E.g. $AND$, $And$, $aNd$, and, And, aNd are all valid replacements for $and$. Note that XQL+ comparison operators ($match$, $no_match$, $isa$, $can$) still require dollar delimiters and are case-sensitive. =item Comparison operator: $match$ or '=~' E.g. "book/title =~ '/(Moby|Dick)/']" will return all book titles containing Moby or Dick. Note that the match expression needs to be quoted and should contain the // or m// delimiters for Perl. When casting the values to be matched, both are converted to Text. =item Comparison operator: $no_match$ or '!~' E.g. "book/title !~ '/(Moby|Dick)/']" will return all book titles that don't contain Moby or Dick. Note that the match expression needs to be quoted and should contain the // or m// delimiters for Perl. When casting the values to be matched, both are converted to Text. =item Comparison operator: $isa$ E.g. '//. $isa$ "XML::XQL::Date"' returns all elements for which the value() function returns an XML::XQL::Date object. (Note that the value() function can be overridden to return a specific object type for certain elements and attributes.) It uses expandType to expand XQL primitive type names. =item Comparison operator: $can$ E.g. '//. $can$ "swim"' returns all elements for which the value() function returns an object that implements the (Perl) swim() method. (Note that the value() function can be overridden to return a specific object type for certain elements and attributes.) =item Function: once (QUERY) E.g. 'once(id("foo"))' will evaluate the QUERY expression only once per query. Certain query results (like the above example) will always return the same value within a query. Using once() will cache the QUERY result for the rest of the query. Note that "constant" function invocations are always cached. See also L =item Function: subst (QUERY, EXPR, EXPR [,MODIFIERS, [MODE]]) E.g. 'subst(book/title, "[M|m]oby", "Dick", "g")' will replace Moby or moby with Dick globally ("g") in all book title elements. Underneath it uses Perl's substitute operator s///. Don't worry about which delimiters are used underneath. The function returns all the book/titles for which a substitution occurred. The default MODIFIERS string is "" (empty.) The function name may be abbreviated to "s". For most Node types, it converts the value() to a string (with xql_toString) to match the string and xql_setValue to set the new value in case it matched. For XQL primitives (Boolean, Number, Text) and other data types (e.g. Date) it uses xql_toString to match the String and xql_setValue to set the result. Beware that performing a substitution on a primitive that was found in the original XQL query expression, changes the value of that constant. If MODE is 0 (default), it treats Element nodes differently by matching and replacing I occurring in the Element node. A text block is defined as the concatenation of the raw text of subsequent Text, CDATASection and EntityReference nodes. In this mode it skips embedded Element nodes. If a text block matches, it is replaced by a single Text node, regardless of the original node type(s). If MODE is 1, it treats Element nodes like the other nodes, i.e. it converts the value() to a string etc. Note that the default implementation of value() calls text(), which normalizes whitespace and includes embedded Element descendants (recursively.) This is probably not what you want to use in most cases, but since I'm not a professional psychic... :-) =item Function: map (QUERY, CODE) E.g. 'map(book/title, "s/[M|m]oby/Dick/g; $_")' will replace Moby or moby with Dick globally ("g") in all book title elements. Underneath it uses Perl's map operator. The function returns all the book/titles for which a change occurred. ??? add more specifics =item Function: eval (EXPR [,TYPE]) Evaluates the Perl expression EXPR and returns an object of the specified TYPE. It uses expandType to expand XQL primitive type names. If the result of the eval was undef, the empty list [] is returned. E.g. 'eval("2 + 5", "Number")' returns a Number object with the value 7, and 'eval("%ENV{USER}")' returns a Text object with the user name. Consider using once() to cache the return value, when the invocation will return the same result for each invocation within a query. ??? add more specifics =item Function: new (TYPE [, QUERY [, PAR] *]) Creates a new object of the specified object TYPE. The constructor may have any number of arguments. The first argument of the constructor (the 2nd argument of the new() function) is considered to be a 'query parameter'. See defineFunction for a definition of I. It uses expandType to expand XQL primitive type names. =item Function: document (QUERY) or doc (QUERY) The document() function creates a new L for each result of QUERY (QUERY may be a simple string expression, like "/usr/enno/file.xml". See t/xql_document.t or below for an example with a more complex QUERY.) document() may be abbreviated to doc(). document() uses an XML::DOM::Parser underneath, which can be set with XML::XQL::setDocParser(). By default it uses a parser that was created without any arguments, i.e. $PARSER = new XML::DOM::Parser; Let's try a more complex example, assuming $doc contains: Then the following query will return two Ls, one for file1.xml and one for file2.xml: @result = XML::XQL::solve ("document(doc/file/@name)", $doc); The resulting documents can be used as input for following queries, e.g. @result = XML::XQL::solve ("document(doc/file/@name)/root/bla", $doc); will return all /root/bla elements from the documents returned by document(). =item Method: DOM_nodeType () Returns the DOM node type. Note that these are mostly the same as nodeType(), except for CDATASection and EntityReference nodes. DOM_nodeType() returns 4 and 5 respectively, whereas nodeType() returns 3, because they are considered text nodes. =item Function wrappers for Perl builtin functions XQL function wrappers have been provided for most Perl builtin functions. When using a Perl builtin function like "substr" in an XQL+ querry, an XQL function wrapper will be generated on the fly. The arguments to these functions may be regular XQL+ subqueries (that return one or more values) for a I (see generateFunction for a definition.) Most wrappers of Perl builtin functions have argument 0 for a query parameter, except for: chmod (parameter 1 is the query parameter), chown (2) and utime (2). The following functions have no query parameter, which means that all parameters should be a single value: atan2, rand, srand, sprintf, rename, unlink, system. The function result is casted to the appropriate XQL primitive type (Number, Text or Boolean), or to an empty list if the result was undef. =back =head2 XPath functions and methods The following functions were found in the XPath specification: =over 4 =item Function: concat (STRING, STRING, STRING*) The concat function returns the concatenation of its arguments. =item Function: starts-with (STRING, STRING) The starts-with function returns true if the first argument string starts with the second argument string, and otherwise returns false. =item Function: contains (STRING, STRING) The contains function returns true if the first argument string contains the second argument string, and otherwise returns false. =item Function: substring-before (STRING, STRING) The substring-before function returns the substring of the first argument string that precedes the first occurrence of the second argument string in the first argument string, or the empty string if the first argument string does not contain the second argument string. For example, substring-before("1999/04/01","/") returns 1999. =item Function: substring-after (STRING, STRING) The substring-after function returns the substring of the first argument string that follows the first occurrence of the second argument string in the first argument string, or the empty string if the first argument string does not contain the second argument string. For example, substring-after("1999/04/01","/") returns 04/01, and substring-after("1999/04/01","19") returns 99/04/01. =item Function: substring (STRING, NUMBER [, NUMBER] ) The substring function returns the substring of the first argument starting at the position specified in the second argument with length specified in the third argument. For example, substring("12345",2,3) returns "234". If the third argument is not specified, it returns the substring starting at the position specified in the second argument and continuing to the end of the string. For example, substring("12345",2) returns "2345". More precisely, each character in the string is considered to have a numeric position: the position of the first character is 1, the position of the second character is 2 and so on. NOTE: This differs from the B method , in which the method treats the position of the first character as 0. The XPath spec says this about rounding, but that is not true in this implementation: I =item Method: string-length ( [ QUERY ] ) The string-length returns the number of characters in the string. If the argument is omitted, it defaults to the context node converted to a string, in other words the string-value of the context node. Note that the generated XQL wrapper for the Perl built-in B does not allow the argument to be omitted. =item Method: normalize-space ( [ QUERY ] ) The normalize-space function returns the argument string with whitespace normalized by stripping leading and trailing whitespace and replacing sequences of whitespace characters by a single space. Whitespace characters are the same as those allowed by the S production in XML. If the argument is omitted, it defaults to the context node converted to a string, in other words the string-value of the context node. =item Function: translate (STRING, STRING, STRING) The translate function returns the first argument string with occurrences of characters in the second argument string replaced by the character at the corresponding position in the third argument string. For example, translate("bar","abc","ABC") returns the string BAr. If there is a character in the second argument string with no character at a corresponding position in the third argument string (because the second argument string is longer than the third argument string), then occurrences of that character in the first argument string are removed. For example, translate("--aaa--","abc-","ABC") returns "AAA". If a character occurs more than once in the second argument string, then the first occurrence determines the replacement character. If the third argument string is longer than the second argument string, then excess characters are ignored. NOTE: The translate function is not a sufficient solution for case conversion in all languages. A future version may provide additional functions for case conversion. This function was implemented using tr///d. =item Function: sum ( QUERY ) The sum function returns the sum of the QUERY results, by converting the string values of each result to a number. =item Function: floor (NUMBER) The floor function returns the largest (closest to positive infinity) number that is not greater than the argument and that is an integer. =item Function: ceiling (NUMBER) The ceiling function returns the smallest (closest to negative infinity) number that is not less than the argument and that is an integer. =item Function: round (NUMBER) The round function returns the number that is closest to the argument and that is an integer. If there are two such numbers, then the one that is closest to positive infinity is returned. =back =head1 Implementation Details =over 4 =item XQL Builtin Data Types The XQL engine uses the following object classes internally. Only Number, Boolean and Text are considered I: =over 4 =item * XML::XQL::Number For integers and floating point numbers. =item * XML::XQL::Boolean For booleans, e.g returned by true() and false(). =item * XML::XQL::Text For string values. =item * XML::XQL::Date For date, time and date/time values. E.g. returned by the date() function. =item * XML::XQL::Node Superclass of all XML node types. E.g. all subclasses of XML::DOM::Node subclass from this. =item * Perl list reference Lists of values are passed by reference (i.e. using [] delimiters). The empty list [] has a double meaning. It also means 'undef' in certain situations, e.g. when a function invocation or comparison failed. =back =item Type casting in comparisons When two values are compared in an XML comparison (e.g. $eq$) the values are first casted to the same data type. Node values are first replaced by their value() (i.e. the XQL value() function is used, which returns a Text value by default, but may return any data type if the user so chooses.) The resulting values are then casted to the type of the object with the highest xql_primType() value. They are as follows: Node (0), Text (1), Number (2), Boolean (3), Date (4), other data types (4 by default, but this may be overriden by the user.) E.g. if one value is a Text value and the other is a Number, the Text value is cast to a Number and the resulting low-level (Perl) comparison is (for $eq$): $number->xql_toString == $text->xql_toString If both were Text values, it would have been $text1->xql_toString eq $text2->xql_toString Note that the XQL spec is vague and even conflicting where it concerns type casting. This implementation resulted after talking to Joe Lapp, one of the spec writers. =item Adding Data Types If you want to add your own data type, make sure it derives from XML::XQL::PrimitiveType and implements the necessary methods. I will add more stuff here to explain it all, but for now, look at the code for the primitive XQL types or the Date class (L in Date.pm.) =item Document Order The XQL spec states that query results always return their values in I, which means the order in which they appeared in the original XML document. Values extracted from Nodes (e.g. with value(), text(), rawText(), nodeName(), etc.) always have a pointer to the reference node (i.e. the Node from which the value was extracted.) These pointers are acknowledged when (intermediate) result lists are sorted. Currently, the only place where a result list is sorted is in a $union$ expression, which is the only place where the result list can be unordered. (If you find that this is not true, let me know.) Non-node values that have no associated reference node, always end up at the end of the result list in the order that they were added. The XQL spec states that the reference node for an XML Attribute is the Element to which it belongs, and that the order of values with the same reference node is undefined. This means that the order of an Element and its attributes would be undefined. But since the XML::DOM module keeps track of the order of the attributes, the XQL engine does the same, and therefore, the attributes of an Element are sorted and appear after their parent Element in a sorted result list. =item Constant Function Invocations If a function always returns the same value when given "constant" arguments, the function is considered to be "constant". A "constant" argument can be either an XQL primitive (Number, Boolean, Text) or a "constant" function invocation. E.g. date("12-03-1998") true() sin(0.3) length("abc") date(substr("12-03-1998 is the date", 0, 10)) are constant, but not: length(book[2]) Results of constant function invocations are cached and calculated only once for each query. See also the CONST parameter in defineFunction. It is not necessary to wrap constant function invocations in a once() call. Constant XQL functions are: date, true, false and a lot of the XQL+ wrappers for Perl builtin functions. Function wrappers for certain builtins are not made constant on purpose to force the invocation to be evaluated every time, e.g. 'mkdir("/user/enno/my_dir", "0644")' (although constant in appearance) may return different results for multiple invocations. See %PerlFunc in Plus.pm for details. =item Function: count ([QUERY]) The count() function has no parameters in the XQL spec. In this implementation it will return the number of QUERY results when passed a QUERY parameter. =item Method: text ([RECURSE]) When expanding an Element node, the text() method adds the expanded text() value of sub-Elements. When RECURSE is set to 0 (default is 1), it will not include sub-elements. This is useful e.g. when using the $match$ operator in a recursive context (using the // operator), so it won't return parent Elements when one of the children matches. =item Method: rawText ([RECURSE]) See text(). =back =head1 SEE ALSO L, L, L The Japanese version of this document can be found on-line at L The L manual page. The Japanese version can be found at L The XQL spec at L The Design of XQL at L The DOM Level 1 specification at L The XML spec (Extensible Markup Language 1.0) at L The L and L manual pages. =head1 AUTHOR Enno Derksen is the original author. Please send bugs, comments and suggestions to T.J. Mather > =cut XML-XQL-0.68/MANIFEST0100644000076500007650000000200707611624523014140 0ustar tjmathertjmatherChanges Makefile.PL MANIFEST lib/XML/XQL.pm lib/XML/XQL/DOM.pm lib/XML/XQL/Date.pm Adds date() method to XML::XQL lib/XML/XQL/Debug.pm lib/XML/XQL/DirXQL.pm lib/XML/XQL/Plus.pm lib/XML/XQL/Query.pod lib/XML/XQL/Strict.pm lib/XML/XQL/Tutorial.pod XML::XQL::Tutorial manual page t/xql_Strict.t t/xql_attr.t t/xql_big.t t/xql_comment.t t/xql_cos.t t/xql_date.t t/xql_document.t t/xql_eval.t t/xql_immed_precedes.t t/xql_index.t t/xql_index2.t t/xql_map.t t/xql_new.t t/xql_once.t t/xql_parent.t t/xql_precedes.t t/xql_recurse.t t/xql_recurse2.t t/xql_sin2.t t/xql_subscript.t t/xql_subscript2.t t/xql_subst.t t/xql_template.t t/xql_test.t t/xql_test_DATA_CKL.t t/xql_text.t t/xql_union.t t/xql_union2.t t/attr2.xml t/attr3.xml XQLParser/Parser.yp YAPP input that produces XQLParser/Parser.pm XQLParser/Makefile.PL XQLParser/Parser.pm Parser for XML::XQL expressions bin/xql.pl bin/README.txt bin/testRules.pl bin/filterInsignifWS.pl samples/REC-xml-19980210.xml samples/bookstore.xml README XML-XQL-0.68/bin/0040755000076500007650000000000007611625246013566 5ustar tjmathertjmatherXML-XQL-0.68/bin/filterInsignifWS.pl0100644000076500007650000000116507000421456017336 0ustar tjmathertjmather# # Usage: perl filterInsignifWS.pl insignif_ws.xml # use XML::DOM::ValParser; # Allow whitespace when ELEMENT rule says EMPTY $XML::Checker::Context::EMPTY::ALLOW_WHITE_SPACE = 1; my $filename = shift; # Uncomment the next line to stop parsing when the first error is encountered. #local $XML::Checker::FAIL = sub { die }; # Uncomment the next line to stop printing error messages #local $XML::Checker::FAIL = sub { }; # Check while building the XML::DOM my $parser = new XML::DOM::ValParser (KeepCDATA => 1, NoExpand => 1, SkipInsignifWS => 1); my $dom = $parser->parsefile ($filename); print $dom->toString; XML-XQL-0.68/bin/testRules.pl0100644000076500007650000000070607000421456016102 0ustar tjmathertjmather# # For debugging the conversion of ELEMENT models to perl regular expressions # use XML::Checker; @expr = ( "(a|b)", "(a?|b+)", "(a|b|c|d|e)", "(a|b)+", "(a,b)", "(a?,b+)", "(a,b,c,d,e)", "(a,b)+", "(head, (p | list | note)*, div*)", "(#PCDATA|a)*", "(#PCDATA|a|b)*", ); for my $expr (@expr) { my $v = new XML::Checker; $v->Element ("bla", $expr); my $rule = $v->{ERule}->{bla}; print "$expr : " . $rule->debug . "\n"; } XML-XQL-0.68/bin/README.txt0100644000076500007650000000072507314125062015254 0ustar tjmathertjmatherThis directory contains some sample Perl scripts. - xql.pl This script will be installed in your perl/bin directory. It is a nice utility that allows you to grep XML files using XQL expressions on the command line. Run xql.pl without any arguments to see the USAGE message. Run the other scripts as follows (after installing the perl modules in this distribution). They should print out errors, warnings and info messages to STDERR. perl script.pl file.xml XML-XQL-0.68/bin/xql.pl0100755000076500007650000001675407016611463014737 0ustar tjmathertjmather#!/home1/enno/bin/perl -Ilib ############################################################################ # Copyright (c) 1998 Enno Derksen # All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. ############################################################################ $USAGE = <"; return $res unless $@; return $str; # all attempts failed } # Replace "\n" with newline etc. $opt_h = extrapolate ($opt_h) if defined ($opt_h); $opt_h = extrapolate ($opt_H) if defined ($opt_H); $opt_s = extrapolate ($opt_s) if defined ($opt_s); $opt_f = extrapolate ($opt_f) if defined ($opt_f); if ($opt_f) { unless ($opt_a) { $opt_a = 0; # count number of format parameters (i.e. number of single %) while ($opt_f =~ /((%)|%%)/g) { defined($2) and $opt_a++; } } } if ($opt_c) { $E_recurse = 1; my $c = 'N'; for (my $i = 0; $i < length $opt_c; $i++) { $_ = substr ($opt_c, $i, 1); /[EATN]/ and do { $c = $_; next; }; /v/ and do { $c =~ /[EN]/ and $E_v = 1; $c =~ /[AN]/ and $A_v = 1; next; }; /t/ and do { $c =~ /[EN]/ and $E_t = 1; $c =~ /[AN]/ and $A_t = 1; $c =~ /[TN]/ and $T_t = 1; next; }; /r/ and do { $c =~ /[EN]/ and $E_r = 1; $c =~ /[AN]/ and $A_r = 1; $c =~ /[TN]/ and $T_r = 1; next; }; /x/ and do { $E_recurse = 0; next; }; die "$0: unexpected character '$_' in -c option '$opt_c'\n"; } } if ($opt_o) { # Prepare reordering array @order = (0 .. $opt_a - 1); # E.g. "1-3,0,4" my $i = 0; while ($opt_o =~ /(\d+)(-(\d+))?/g) { if (defined $3) # range { for (my $j = $1; $j <= $3; $j++) { $order[$j] = $i++; } } else { $order[$1] = $i++; } } } sub reorder { my @par = (); for (my $i = 0; $i < @order; $i++) { push @par, $_[$order[$i]]; } @par; } eval $opt_p if $opt_p; die "$0: bad code (-p option) code=[$opt_p]: $@" if $@; my $query; eval { $query = new XML::XQL::Query (Expr => $query_expr, @options); }; die "$0: invalid query expression: $@" if $@; my $parser = new XML::DOM::Parser; sub transform { my $val = shift; return $val unless defined $val; # skip undef my $type = ref($val); return $val unless $type; # skip scalars if ($type eq "ARRAY") { if (@$val == 0) # empty list / undef { #??? not sure what to do here return "[]"; } else { #??? not sure what to do here } } elsif ($val->isa ('XML::XQL::Node')) { my $nodeType = $val->xql_nodeType; if ($nodeType == 1) # element node { if ($E_v) { return transform ($val->xql_value); } elsif ($E_t) { return $val->xql_text ($E_recurse); } elsif ($E_r) { return $val->xql_rawText ($E_recurse); } } elsif ($nodeType == 2) # attribute node { if ($A_v) { return transform ($val->xql_value); } elsif ($A_t) { return $val->xql_text; } elsif ($A_r) { return $val->xql_rawText; } } elsif ($nodeType == 3) # text node (also CDATASection, EntityRef) { if ($T_t) { return $val->xql_text; } elsif ($T_r) { return $val->xql_rawText; } } $val->xql_xmlString; } elsif ($val->isa ('XML::XQL::PrimitiveType')) { #?? could add xql_normalString $val->xql_toString; } else # ??? { "$val"; } } sub solveQuery { my ($dom, $file) = @_; my @result = $query->solve ($dom); if ($opt_m) { #?? what if no results if ($opt_b) { # backup original XML file my $bak_file = $file . $opt_b; unless (rename ($file, $bak_file)) { warn "$0: can't backup $file to $bak_file (skipping)"; next; } } if ($opt_r) # replace original file { eval { $dom->printToFile ($file); }; if ($@) { warn "$0: can't open $file for writing (skipping): $@"; next; } } else # print modified file to STDOUT { $dom->printToFileHandle (\*STDOUT); } } else # print query results { # transform query results @result = map { transform ($_) } @result; # print file header # (don't print it if -H was specified and no results were found) printf ($opt_h, $file) if $opt_h && (!$opt_H || @result); if ($opt_f) { my $j = 0; my $ii = $opt_a - 1; for (my $i = 0; $i < @result; $i += $opt_a, $ii += $opt_a, $j++) { printf ($opt_s, $j) if $opt_s; # record header my @par = @result[$i .. $ii]; @par = reorder (@par) if $opt_o; printf ($opt_f, @par); } } else { for (my $i = 0; $i < @result; $i++) { printf ($opt_s, $i) if $opt_s; # record header print $result[$i]; print "\n" unless $opt_n; } } } } if (@ARGV) { for my $file (@ARGV) { my $dom = $parser->parsefile ($file); if ($@) { warn "$0: bad XML file '$file' (skipping)"; next; } solveQuery ($dom, $file); $dom->dispose; } } else # read from STDIN { my $dom = $parser->parse (*STDIN); solveQuery ($dom, "(input)"); $dom->dispose; } XML-XQL-0.68/XQLParser/0040755000076500007650000000000007611625246014637 5ustar tjmathertjmatherXML-XQL-0.68/XQLParser/Parser.pm0100644000076500007650000005431307245610065016430 0ustar tjmathertjmather#################################################################### # # This file was generated using Parse::Yapp version 1.03. # # Don't edit this file, use source file instead. # # ANY CHANGE MADE HERE WILL BE LOST ! # #################################################################### package XML::XQL::Parser; use vars qw ( @ISA ); use strict; @ISA= qw ( Parse::Yapp::Driver ); use Parse::Yapp::Driver; sub new { my($class)=shift; ref($class) and $class=ref($class); my($self)=$class->SUPER::new( yyversion => '1.03', yystates => [ {#State 0 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11, "not" => 17 }, GOTOS => { 'WildQName' => 19, 'WildNCName' => 18, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'Conjunction' => 5, 'Disjunction' => 6, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Negation' => 26, 'Query' => 27, 'Intersection' => 15, 'Bang' => 30, 'Sequence' => 31, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 1 ACTIONS => { "[" => 36 }, DEFAULT => -51, GOTOS => { 'Subscript_2' => 37 } }, {#State 2 DEFAULT => -43 }, {#State 3 ACTIONS => { 'MATCH' => 40, 'COMPARE' => 39 }, GOTOS => { 'ComparisonOp' => 38 } }, {#State 4 DEFAULT => -65 }, {#State 5 ACTIONS => { "or" => 41 }, DEFAULT => -21 }, {#State 6 ACTIONS => { 'SeqOp' => 42 }, DEFAULT => -19 }, {#State 7 DEFAULT => -67 }, {#State 8 DEFAULT => -59 }, {#State 9 DEFAULT => -42 }, {#State 10 ACTIONS => { 'COMPARE' => -37, 'MATCH' => -37 }, DEFAULT => -33 }, {#State 11 ACTIONS => { "*" => 29, 'NCName' => 25 }, GOTOS => { 'WildQName' => 43, 'WildNCName' => 18 } }, {#State 12 DEFAULT => -62 }, {#State 13 DEFAULT => -68 }, {#State 14 ACTIONS => { 'NCName' => 25, "(" => 28, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Filter' => 1, 'Bang' => 30, 'RelativePath' => 2, 'LValue' => 44, 'Invocation' => 32, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 45, 'Subscript' => 35 } }, {#State 15 ACTIONS => { 'UnionOp' => 46 }, DEFAULT => -27 }, {#State 16 ACTIONS => { ".." => -17, 'XQLName_Paren' => -17, "\@" => -17, 'NCName' => -17, "(" => -17, "*" => -17, "." => -17 }, DEFAULT => -44 }, {#State 17 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11, "not" => 17 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Negation' => 47, 'Intersection' => 15, 'Bang' => 30, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 18 ACTIONS => { ":" => 48 }, DEFAULT => -4 }, {#State 19 DEFAULT => -10 }, {#State 20 ACTIONS => { 'NCName' => 25, "(" => 28, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Filter' => 1, 'Bang' => 30, 'RelativePath' => 2, 'LValue' => 49, 'Invocation' => 32, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 45, 'Subscript' => 35 } }, {#State 21 DEFAULT => -25 }, {#State 22 ACTIONS => { 'NCName' => 25, 'TEXT' => 50, "(" => 28, "any" => 14, "all" => 20, ")" => 54, "*" => 29, 'NUMBER' => 51, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11, 'INTEGER' => 53, "not" => 17 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'Conjunction' => 5, 'Disjunction' => 52, 'Invocation_2' => 55, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'Param' => 56, 'RelativeTerm' => 12, 'Negation' => 26, 'AttributeName' => 13, 'Intersection' => 15, 'Bang' => 30, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 23 DEFAULT => -18 }, {#State 24 ACTIONS => { "*" => 29, 'NCName' => 25, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "(" => 28, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Filter' => 1, 'Bang' => 30, 'RelativePath' => 57, 'Invocation' => 32, 'ElementName' => 7, 'Grouping' => 8, 'Subscript' => 35 } }, {#State 25 DEFAULT => -2 }, {#State 26 ACTIONS => { "and" => 58 }, DEFAULT => -23 }, {#State 27 ACTIONS => { '' => 59 } }, {#State 28 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11, "not" => 17 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'Conjunction' => 5, 'Disjunction' => 6, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Negation' => 26, 'Query' => 60, 'Intersection' => 15, 'Bang' => 30, 'Sequence' => 31, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 29 DEFAULT => -3 }, {#State 30 ACTIONS => { "//" => 23, "/" => 61 }, DEFAULT => -46, GOTOS => { 'PathOp' => 62 } }, {#State 31 DEFAULT => -1 }, {#State 32 DEFAULT => -66 }, {#State 33 ACTIONS => { "intersect" => 63 }, DEFAULT => -29 }, {#State 34 DEFAULT => -64 }, {#State 35 ACTIONS => { "!" => 64 }, DEFAULT => -48 }, {#State 36 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, 'INTEGER' => 65, "\@" => 11, "not" => 17 }, GOTOS => { 'Subquery' => 67, 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'Conjunction' => 5, 'Disjunction' => 6, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Range' => 68, 'Path' => 10, 'IndexArg' => 69, 'RelativeTerm' => 12, 'IndexList' => 66, 'AttributeName' => 13, 'Negation' => 26, 'Query' => 70, 'Intersection' => 15, 'Bang' => 30, 'Sequence' => 31, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 37 DEFAULT => -50 }, {#State 38 ACTIONS => { 'NCName' => 25, 'TEXT' => 71, "(" => 28, "*" => 29, 'NUMBER' => 72, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, 'INTEGER' => 74, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Filter' => 1, 'Bang' => 30, 'RelativePath' => 2, 'Invocation' => 32, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 73, 'Subscript' => 35, 'RValue' => 75 } }, {#State 39 DEFAULT => -31 }, {#State 40 DEFAULT => -32 }, {#State 41 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11, "not" => 17 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'Conjunction' => 5, 'Disjunction' => 76, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Negation' => 26, 'Intersection' => 15, 'Bang' => 30, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 42 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11, "not" => 17 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'Conjunction' => 5, 'Disjunction' => 6, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Negation' => 26, 'Intersection' => 15, 'Bang' => 30, 'Sequence' => 77, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 43 DEFAULT => -11 }, {#State 44 ACTIONS => { 'MATCH' => 40, 'COMPARE' => 39 }, GOTOS => { 'ComparisonOp' => 78 } }, {#State 45 DEFAULT => -37 }, {#State 46 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 79, 'RelativePath' => 2, 'LValue' => 3, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Intersection' => 15, 'Bang' => 30, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 47 DEFAULT => -26 }, {#State 48 ACTIONS => { "*" => 29, 'NCName' => 25 }, GOTOS => { 'WildNCName' => 80 } }, {#State 49 ACTIONS => { 'MATCH' => 40, 'COMPARE' => 39 }, GOTOS => { 'ComparisonOp' => 81 } }, {#State 50 DEFAULT => -9 }, {#State 51 DEFAULT => -8 }, {#State 52 DEFAULT => -6 }, {#State 53 DEFAULT => -7 }, {#State 54 DEFAULT => -13 }, {#State 55 DEFAULT => -12 }, {#State 56 ACTIONS => { "," => 83 }, DEFAULT => -15, GOTOS => { 'Invocation_3' => 82 } }, {#State 57 DEFAULT => -45 }, {#State 58 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11, "not" => 17 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'Conjunction' => 84, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Negation' => 26, 'Intersection' => 15, 'Bang' => 30, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 59 DEFAULT => -0 }, {#State 60 ACTIONS => { ")" => 85 } }, {#State 61 DEFAULT => -17 }, {#State 62 ACTIONS => { "*" => 29, 'NCName' => 25, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "(" => 28, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Filter' => 1, 'Bang' => 30, 'RelativePath' => 86, 'Invocation' => 32, 'ElementName' => 7, 'Grouping' => 8, 'Subscript' => 35 } }, {#State 63 ACTIONS => { 'NCName' => 25, "(" => 28, "any" => 14, "all" => 20, "*" => 29, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'RelativePath' => 2, 'LValue' => 3, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Intersection' => 87, 'Bang' => 30, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 64 ACTIONS => { 'XQLName_Paren' => 22 }, GOTOS => { 'Invocation' => 88 } }, {#State 65 ACTIONS => { "to" => 89 }, DEFAULT => -56 }, {#State 66 ACTIONS => { "]" => 90 } }, {#State 67 ACTIONS => { "]" => 91 } }, {#State 68 DEFAULT => -57 }, {#State 69 ACTIONS => { "," => 93 }, DEFAULT => -54, GOTOS => { 'IndexList_2' => 92 } }, {#State 70 DEFAULT => -61 }, {#State 71 DEFAULT => -41 }, {#State 72 DEFAULT => -40 }, {#State 73 DEFAULT => -38 }, {#State 74 DEFAULT => -39 }, {#State 75 DEFAULT => -34 }, {#State 76 DEFAULT => -22 }, {#State 77 DEFAULT => -20 }, {#State 78 ACTIONS => { 'NCName' => 25, 'TEXT' => 71, "(" => 28, "*" => 29, 'NUMBER' => 72, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, 'INTEGER' => 74, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Filter' => 1, 'Bang' => 30, 'RelativePath' => 2, 'Invocation' => 32, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 73, 'Subscript' => 35, 'RValue' => 94 } }, {#State 79 DEFAULT => -28 }, {#State 80 DEFAULT => -5 }, {#State 81 ACTIONS => { 'NCName' => 25, 'TEXT' => 71, "(" => 28, "*" => 29, 'NUMBER' => 72, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, 'INTEGER' => 74, "\@" => 11 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'RelativeTerm' => 12, 'AttributeName' => 13, 'Filter' => 1, 'Bang' => 30, 'RelativePath' => 2, 'Invocation' => 32, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 73, 'Subscript' => 35, 'RValue' => 95 } }, {#State 82 ACTIONS => { ")" => 96 } }, {#State 83 ACTIONS => { 'NCName' => 25, 'TEXT' => 50, "(" => 28, "any" => 14, "all" => 20, "*" => 29, 'NUMBER' => 51, ".." => 4, 'XQLName_Paren' => 22, "." => 34, "//" => 23, "/" => 16, "\@" => 11, 'INTEGER' => 53, "not" => 17 }, GOTOS => { 'WildNCName' => 18, 'WildQName' => 19, 'Filter' => 1, 'Union' => 21, 'RelativePath' => 2, 'LValue' => 3, 'Conjunction' => 5, 'Disjunction' => 52, 'ElementName' => 7, 'Grouping' => 8, 'PathOp' => 24, 'AbsolutePath' => 9, 'Path' => 10, 'Param' => 97, 'RelativeTerm' => 12, 'Negation' => 26, 'AttributeName' => 13, 'Intersection' => 15, 'Bang' => 30, 'Invocation' => 32, 'Comparison' => 33, 'Subscript' => 35 } }, {#State 84 DEFAULT => -24 }, {#State 85 DEFAULT => -63 }, {#State 86 DEFAULT => -47 }, {#State 87 DEFAULT => -30 }, {#State 88 DEFAULT => -49 }, {#State 89 ACTIONS => { 'INTEGER' => 98 } }, {#State 90 DEFAULT => -52 }, {#State 91 DEFAULT => -60 }, {#State 92 DEFAULT => -53 }, {#State 93 ACTIONS => { 'INTEGER' => 65 }, GOTOS => { 'IndexArg' => 99, 'Range' => 68 } }, {#State 94 DEFAULT => -35 }, {#State 95 DEFAULT => -36 }, {#State 96 DEFAULT => -14 }, {#State 97 ACTIONS => { "," => 83 }, DEFAULT => -15, GOTOS => { 'Invocation_3' => 100 } }, {#State 98 DEFAULT => -58 }, {#State 99 ACTIONS => { "," => 93 }, DEFAULT => -54, GOTOS => { 'IndexList_2' => 101 } }, {#State 100 DEFAULT => -16 }, {#State 101 DEFAULT => -55 } ], yyrules => [ [#Rule 0 '$start', 2, undef ], [#Rule 1 'Query', 1, undef ], [#Rule 2 'WildNCName', 1, undef ], [#Rule 3 'WildNCName', 1, undef ], [#Rule 4 'WildQName', 1, sub #line 24 "Parser.yp" { [ Name => $_[1] ]; } ], [#Rule 5 'WildQName', 3, sub #line 25 "Parser.yp" { [ NameSpace => $_[1], Name => $_[2]]; } ], [#Rule 6 'Param', 1, undef ], [#Rule 7 'Param', 1, sub #line 30 "Parser.yp" { new XML::XQL::Number ($_[1]); } ], [#Rule 8 'Param', 1, sub #line 31 "Parser.yp" { new XML::XQL::Number ($_[1]); } ], [#Rule 9 'Param', 1, sub #line 32 "Parser.yp" { new XML::XQL::Text ($_[1]); } ], [#Rule 10 'ElementName', 1, sub #line 35 "Parser.yp" { new XML::XQL::Element (@{$_[1]}); } ], [#Rule 11 'AttributeName', 2, sub #line 38 "Parser.yp" { new XML::XQL::Attribute (@{$_[2]}); } ], [#Rule 12 'Invocation', 2, sub #line 41 "Parser.yp" { my ($func, $type) = $_[0]->{Query}->findFunctionOrMethod ($_[1], $_[2]); new XML::XQL::Invocation (Name => $_[1], Args => $_[2], Func => $func, Type => $type); } ], [#Rule 13 'Invocation_2', 1, sub #line 50 "Parser.yp" { [] } ], [#Rule 14 'Invocation_2', 3, sub #line 51 "Parser.yp" { unshift @{$_[2]}, $_[1]; $_[2]; } ], [#Rule 15 'Invocation_3', 0, sub #line 54 "Parser.yp" { [] } ], [#Rule 16 'Invocation_3', 3, sub #line 55 "Parser.yp" { unshift @{$_[3]}, $_[2]; $_[3]; } ], [#Rule 17 'PathOp', 1, undef ], [#Rule 18 'PathOp', 1, undef ], [#Rule 19 'Sequence', 1, undef ], [#Rule 20 'Sequence', 3, sub #line 62 "Parser.yp" { new XML::XQL::Sequence (Left => $_[1], Oper => $_[2], Right => $_[3]); } ], [#Rule 21 'Disjunction', 1, undef ], [#Rule 22 'Disjunction', 3, sub #line 68 "Parser.yp" { new XML::XQL::Or (Left => $_[1], Right => $_[3]); } ], [#Rule 23 'Conjunction', 1, undef ], [#Rule 24 'Conjunction', 3, sub #line 73 "Parser.yp" { new XML::XQL::And (Left => $_[1], Right => $_[3]); } ], [#Rule 25 'Negation', 1, undef ], [#Rule 26 'Negation', 2, sub #line 78 "Parser.yp" { new XML::XQL::Not (Left => $_[2]); } ], [#Rule 27 'Union', 1, undef ], [#Rule 28 'Union', 3, sub #line 82 "Parser.yp" { new XML::XQL::Union (Left => $_[1], Right => $_[3]); } ], [#Rule 29 'Intersection', 1, undef ], [#Rule 30 'Intersection', 3, sub #line 87 "Parser.yp" { new XML::XQL::Intersect (Left => $_[1], Right => $_[3]); } ], [#Rule 31 'ComparisonOp', 1, sub #line 91 "Parser.yp" { [ $_[1], $_[0]->{Query}->findComparisonOperator ($_[1]) ]; } ], [#Rule 32 'ComparisonOp', 1, sub #line 93 "Parser.yp" { [ $_[1], $_[0]->{Query}->findComparisonOperator ($_[1]) ]; } ], [#Rule 33 'Comparison', 1, undef ], [#Rule 34 'Comparison', 3, sub #line 98 "Parser.yp" { new XML::XQL::Compare (All => 0, Left => $_[1], Oper => $_[2]->[0], Func => $_[2]->[1], Right => $_[3]); } ], [#Rule 35 'Comparison', 4, sub #line 102 "Parser.yp" { new XML::XQL::Compare (All => 0, Left => $_[2], Oper => $_[3]->[0], Func => $_[3]->[1], Right => $_[4]); } ], [#Rule 36 'Comparison', 4, sub #line 106 "Parser.yp" { new XML::XQL::Compare (All => 1, Left => $_[2], Oper => $_[3]->[0], Func => $_[3]->[1], Right => $_[4]); } ], [#Rule 37 'LValue', 1, undef ], [#Rule 38 'RValue', 1, undef ], [#Rule 39 'RValue', 1, sub #line 116 "Parser.yp" { new XML::XQL::Number ($_[1]); } ], [#Rule 40 'RValue', 1, sub #line 117 "Parser.yp" { new XML::XQL::Number ($_[1]); } ], [#Rule 41 'RValue', 1, sub #line 118 "Parser.yp" { new XML::XQL::Text ($_[1]); } ], [#Rule 42 'Path', 1, undef ], [#Rule 43 'Path', 1, undef ], [#Rule 44 'AbsolutePath', 1, sub #line 124 "Parser.yp" { new XML::Root; } ], [#Rule 45 'AbsolutePath', 2, sub #line 125 "Parser.yp" { new XML::XQL::Path (PathOp => $_[1], Right => $_[2]); } ], [#Rule 46 'RelativePath', 1, undef ], [#Rule 47 'RelativePath', 3, sub #line 130 "Parser.yp" { new XML::XQL::Path (Left => $_[1], PathOp => $_[2], Right => $_[3]); } ], [#Rule 48 'Bang', 1, undef ], [#Rule 49 'Bang', 3, sub #line 136 "Parser.yp" { XML::XQL::parseError ("only methods (not functions) can be used after the Bang (near '!" . $_[3]->{Name} . "'") unless $_[3]->isMethod; new XML::XQL::Bang (Left => $_[1], Right => $_[3]); } ], [#Rule 50 'Subscript', 2, sub #line 144 "Parser.yp" { defined($_[2]) ? new XML::XQL::Subscript (Left => $_[1], IndexList => $_[2]) : $_[1]; } ], [#Rule 51 'Subscript_2', 0, undef ], [#Rule 52 'Subscript_2', 3, sub #line 151 "Parser.yp" { $_[2]; } ], [#Rule 53 'IndexList', 2, sub #line 156 "Parser.yp" { push (@{$_[1]}, @{$_[2]}); $_[1]; } ], [#Rule 54 'IndexList_2', 0, sub #line 159 "Parser.yp" { [] } ], [#Rule 55 'IndexList_2', 3, sub #line 160 "Parser.yp" { push (@{$_[2]}, @{$_[3]}); $_[2]; } ], [#Rule 56 'IndexArg', 1, sub #line 163 "Parser.yp" { [ $_[1], $_[1] ]; } ], [#Rule 57 'IndexArg', 1, undef ], [#Rule 58 'Range', 3, sub #line 167 "Parser.yp" { # Syntactic Constraint 9: # If both integers are positive or if both integers are # negative, the first integer must be less than or # equal to the second integer. XML::XQL::parseError ( "$_[1] should be less than $_[3] in '$_[1] $_[2] $_[3]'") if ($_[1] > $_[3] && ($_[1] < 0) == ($_[3] < 0)); [ $_[1], $_[3] ]; } ], [#Rule 59 'Filter', 1, undef ], [#Rule 60 'Filter', 4, sub #line 180 "Parser.yp" { new XML::XQL::Filter (Left => $_[1], Right => $_[3]); } ], [#Rule 61 'Subquery', 1, undef ], [#Rule 62 'Grouping', 1, undef ], [#Rule 63 'Grouping', 3, sub #line 189 "Parser.yp" { $_[2]; } ], [#Rule 64 'RelativeTerm', 1, sub #line 192 "Parser.yp" { new XML::XQL::Current; } ], [#Rule 65 'RelativeTerm', 1, sub #line 193 "Parser.yp" { new XML::XQL::Parent; } ], [#Rule 66 'RelativeTerm', 1, undef ], [#Rule 67 'RelativeTerm', 1, undef ], [#Rule 68 'RelativeTerm', 1, undef ] ], @_); bless($self,$class); } #line 199 "Parser.yp" 1; XML-XQL-0.68/XQLParser/Parser.yp0100644000076500007650000001074007221054151016430 0ustar tjmathertjmather%left SeqOp %left 'or' %left 'and' %left 'not' %left UnionOp %left 'intersect' %left COMPARE %left MATCH %left '/' '//' %left '!' %left '[' ']' %left '(' ')' %% Query: Sequence ; WildNCName: NCName | '*' ; #?? not sure about NCName WildQName: WildNCName { [ Name => $_[1] ]; } | WildNCName ':' WildNCName { [ NameSpace => $_[1], Name => $_[2]]; } ; Param: Disjunction | INTEGER { new XML::XQL::Number ($_[1]); } | NUMBER { new XML::XQL::Number ($_[1]); } | TEXT { new XML::XQL::Text ($_[1]); } ; ElementName: WildQName { new XML::XQL::Element (@{$_[1]}); } ; AttributeName: '@' WildQName { new XML::XQL::Attribute (@{$_[2]}); } ; Invocation: XQLName_Paren Invocation_2 { my ($func, $type) = $_[0]->{Query}->findFunctionOrMethod ($_[1], $_[2]); new XML::XQL::Invocation (Name => $_[1], Args => $_[2], Func => $func, Type => $type); } ; Invocation_2: ')' { [] } | Param Invocation_3 ')' { unshift @{$_[2]}, $_[1]; $_[2]; } ; Invocation_3: /* empty */ { [] } | ',' Param Invocation_3 { unshift @{$_[3]}, $_[2]; $_[3]; } ; PathOp: '/' | '//' ; Sequence: Disjunction | Disjunction SeqOp Sequence { new XML::XQL::Sequence (Left => $_[1], Oper => $_[2], Right => $_[3]); } ; Disjunction: Conjunction | Conjunction 'or' Disjunction { new XML::XQL::Or (Left => $_[1], Right => $_[3]); } ; Conjunction: Negation | Negation 'and' Conjunction { new XML::XQL::And (Left => $_[1], Right => $_[3]); } ; Negation: Union | 'not' Negation { new XML::XQL::Not (Left => $_[2]); } ; Union: Intersection | Intersection UnionOp Union { new XML::XQL::Union (Left => $_[1], Right => $_[3]); } ; Intersection: Comparison | Comparison 'intersect' Intersection { new XML::XQL::Intersect (Left => $_[1], Right => $_[3]); } ; ComparisonOp: COMPARE { [ $_[1], $_[0]->{Query}->findComparisonOperator ($_[1]) ]; } | MATCH { [ $_[1], $_[0]->{Query}->findComparisonOperator ($_[1]) ]; } ; Comparison: Path | LValue ComparisonOp RValue { new XML::XQL::Compare (All => 0, Left => $_[1], Oper => $_[2]->[0], Func => $_[2]->[1], Right => $_[3]); } | 'any' LValue ComparisonOp RValue { new XML::XQL::Compare (All => 0, Left => $_[2], Oper => $_[3]->[0], Func => $_[3]->[1], Right => $_[4]); } | 'all' LValue ComparisonOp RValue { new XML::XQL::Compare (All => 1, Left => $_[2], Oper => $_[3]->[0], Func => $_[3]->[1], Right => $_[4]); } ; LValue: Path ; RValue: Path | INTEGER { new XML::XQL::Number ($_[1]); } | NUMBER { new XML::XQL::Number ($_[1]); } | TEXT { new XML::XQL::Text ($_[1]); } ; Path: AbsolutePath | RelativePath ; AbsolutePath: '/' { new XML::Root; } | PathOp RelativePath { new XML::XQL::Path (PathOp => $_[1], Right => $_[2]); } ; RelativePath: Bang | Bang PathOp RelativePath { new XML::XQL::Path (Left => $_[1], PathOp => $_[2], Right => $_[3]); } ; Bang: Subscript | Subscript '!' Invocation { XML::XQL::parseError ("only methods (not functions) can be used after the Bang (near '!" . $_[3]->{Name} . "'") unless $_[3]->isMethod; new XML::XQL::Bang (Left => $_[1], Right => $_[3]); } ; Subscript: Filter Subscript_2 { defined($_[2]) ? new XML::XQL::Subscript (Left => $_[1], IndexList => $_[2]) : $_[1]; } ; Subscript_2: /* empty */ | '[' IndexList ']' { $_[2]; } #?? The following line *IS* part of the XQL spec, but it doesn't make sense #?? | '[' ']' ; IndexList: IndexArg IndexList_2 { push (@{$_[1]}, @{$_[2]}); $_[1]; } ; IndexList_2: /* empty */ { [] } | ',' IndexArg IndexList_2 { push (@{$_[2]}, @{$_[3]}); $_[2]; } ; IndexArg: INTEGER { [ $_[1], $_[1] ]; } | Range ; Range: INTEGER 'to' INTEGER { # Syntactic Constraint 9: # If both integers are positive or if both integers are # negative, the first integer must be less than or # equal to the second integer. XML::XQL::parseError ( "$_[1] should be less than $_[3] in '$_[1] $_[2] $_[3]'") if ($_[1] > $_[3] && ($_[1] < 0) == ($_[3] < 0)); [ $_[1], $_[3] ]; } ; Filter: Grouping | Filter '[' Subquery ']' { new XML::XQL::Filter (Left => $_[1], Right => $_[3]); } ; #?? Eliminate Subquery Subquery: Query ; Grouping: RelativeTerm | '(' Query ')' { $_[2]; } ; RelativeTerm: '.' { new XML::XQL::Current; } | '..' { new XML::XQL::Parent; } | Invocation | ElementName | AttributeName ; %% XML-XQL-0.68/XQLParser/Makefile.PL0100644000076500007650000000070007233774474016613 0ustar tjmathertjmatheruse ExtUtils::MakeMaker; WriteMakefile( NAME => 'XML::XQL::Parser', PREREQ_PM => { Parse::Yapp => '0' }, PM => { 'Parser.pm' => '$(INST_LIBDIR)/Parser.pm' }, # Is this cheating or this this the only way to do it? # Note: yapp comes with Parse::Yapp depend => { 'Parser.pm' => "Parser.yp\n\t\@\$(FULLPERL) \$(INSTALLBIN)/yapp -m XML::XQL::Parser Parser.yp > Parser.pm" }, ); XML-XQL-0.68/samples/0040755000076500007650000000000007611625246014462 5ustar tjmathertjmatherXML-XQL-0.68/samples/bookstore.xml0100644000076500007650000000353407000402576017204 0ustar tjmathertjmather Seven Years in Trenton Joe Bob Trenton Literary Review Honorable Mention 12 History of Trenton Mary Bob Selected Short Stories of Mary Bob 55 Tracking Trenton 2.50 Trenton Today, Trenton Tomorrow Toni Bob B.A. Ph.D. Pulizer Still in Trenton Trenton Forever 6.50

It was a dark and stormy night.

But then all nights in Trenton seem dark and stormy to someone who has gone through what I have.

Trenton misery
Who's Who in Trenton Robert Bob
XML-XQL-0.68/samples/REC-xml-19980210.xml0100644000076500007650000046717506777463755017370 0ustar tjmathertjmather "> '"> amp, lt, gt, apos, quot"> ]>
Extensible Markup Language (XML) 1.0 REC-xml-&iso6.doc.date; W3C Recommendation &draft.day;&draft.month;&draft.year; http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date; http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date;.xml http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date;.html http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date;.pdf http://www.w3.org/TR/1998/REC-xml-&iso6.doc.date;.ps http://www.w3.org/TR/REC-xml http://www.w3.org/TR/PR-xml-971208 Tim Bray Textuality and Netscape tbray@textuality.com Jean Paoli Microsoft jeanpa@microsoft.com C. M. Sperberg-McQueen University of Illinois at Chicago cmsmcq@uic.edu

The Extensible Markup Language (XML) is a subset of SGML that is completely described in this document. Its goal is to enable generic SGML to be served, received, and processed on the Web in the way that is now possible with HTML. XML has been designed for ease of implementation and for interoperability with both SGML and HTML.

This document has been reviewed by W3C Members and other interested parties and has been endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited as a normative reference from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.

This document specifies a syntax created by subsetting an existing, widely used international text processing standard (Standard Generalized Markup Language, ISO 8879:1986(E) as amended and corrected) for use on the World Wide Web. It is a product of the W3C XML Activity, details of which can be found at http://www.w3.org/XML. A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR.

This specification uses the term URI, which is defined by , a work in progress expected to update and .

The list of known errors in this specification is available at http://www.w3.org/XML/xml-19980210-errata.

Please report errors in this document to xml-editor@w3.org.

Chicago, Vancouver, Mountain View, et al.: World-Wide Web Consortium, XML Working Group, 1996, 1997.

Created in electronic form.

English Extended Backus-Naur Form (formal grammar) 1997-12-03 : CMSMcQ : yet further changes 1997-12-02 : TB : further changes (see TB to XML WG, 2 December 1997) 1997-12-02 : CMSMcQ : deal with as many corrections and comments from the proofreaders as possible: entify hard-coded document date in pubdate element, change expansion of entity WebSGML, update status description as per Dan Connolly (am not sure about refernece to Berners-Lee et al.), add 'The' to abstract as per WG decision, move Relationship to Existing Standards to back matter and combine with References, re-order back matter so normative appendices come first, re-tag back matter so informative appendices are tagged informdiv1, remove XXX XXX from list of 'normative' specs in prose, move some references from Other References to Normative References, add RFC 1738, 1808, and 2141 to Other References (they are not normative since we do not require the processor to enforce any rules based on them), add reference to 'Fielding draft' (Berners-Lee et al.), move notation section to end of body, drop URIchar non-terminal and use SkipLit instead, lose stray reference to defunct nonterminal 'markupdecls', move reference to Aho et al. into appendix (Tim's right), add prose note saying that hash marks and fragment identifiers are NOT part of the URI formally speaking, and are NOT legal in system identifiers (processor 'may' signal an error). Work through: Tim Bray reacting to James Clark, Tim Bray on his own, Eve Maler, NOT DONE YET: change binary / text to unparsed / parsed. handle James's suggestion about < in attriubte values uppercase hex characters, namechar list, 1997-12-01 : JB : add some column-width parameters 1997-12-01 : CMSMcQ : begin round of changes to incorporate recent WG decisions and other corrections: binding sources of character encoding info (27 Aug / 3 Sept), correct wording of Faust quotation (restore dropped line), drop SDD from EncodingDecl, change text at version number 1.0, drop misleading (wrong!) sentence about ignorables and extenders, modify definition of PCData to make bar on msc grammatical, change grammar's handling of internal subset (drop non-terminal markupdecls), change definition of includeSect to allow conditional sections, add integral-declaration constraint on internal subset, drop misleading / dangerous sentence about relationship of entities with system storage objects, change table body tag to htbody as per EM change to DTD, add rule about space normalization in public identifiers, add description of how to generate our name-space rules from Unicode character database (needs further work!). 1997-10-08 : TB : Removed %-constructs again, new rules for PE appearance. 1997-10-01 : TB : Case-sensitive markup; cleaned up element-type defs, lotsa little edits for style 1997-09-25 : TB : Change to elm's new DTD, with substantial detail cleanup as a side-effect 1997-07-24 : CMSMcQ : correct error (lost *) in definition of ignoreSectContents (thanks to Makoto Murata) Allow all empty elements to have end-tags, consistent with SGML TC (as per JJC). 1997-07-23 : CMSMcQ : pre-emptive strike on pending corrections: introduce the term 'empty-element tag', note that all empty elements may use it, and elements declared EMPTY must use it. Add WFC requiring encoding decl to come first in an entity. Redefine notations to point to PIs as well as binary entities. Change autodetection table by removing bytes 3 and 4 from examples with Byte Order Mark. Add content model as a term and clarify that it applies to both mixed and element content. 1997-06-30 : CMSMcQ : change date, some cosmetic changes, changes to productions for choice, seq, Mixed, NotationType, Enumeration. Follow James Clark's suggestion and prohibit conditional sections in internal subset. TO DO: simplify production for ignored sections as a result, since we don't need to worry about parsers which don't expand PErefs finding a conditional section. 1997-06-29 : TB : various edits 1997-06-29 : CMSMcQ : further changes: Suppress old FINAL EDIT comments and some dead material. Revise occurrences of % in grammar to exploit Henry Thompson's pun, especially markupdecl and attdef. Remove RMD requirement relating to element content (?). 1997-06-28 : CMSMcQ : Various changes for 1 July draft: Add text for draconian error handling (introduce the term Fatal Error). RE deleta est (changing wording from original announcement to restrict the requirement to validating parsers). Tag definition of validating processor and link to it. Add colon as name character. Change def of %operator. Change standard definitions of lt, gt, amp. Strip leading zeros from #x00nn forms. 1997-04-02 : CMSMcQ : final corrections of editorial errors found in last night's proofreading. Reverse course once more on well-formed: Webster's Second hyphenates it, and that's enough for me. 1997-04-01 : CMSMcQ : corrections from JJC, EM, HT, and self 1997-03-31 : Tim Bray : many changes 1997-03-29 : CMSMcQ : some Henry Thompson (on entity handling), some Charles Goldfarb, some ERB decisions (PE handling in miscellaneous declarations. Changed Ident element to accept def attribute. Allow normalization of Unicode characters. move def of systemliteral into section on literals. 1997-03-28 : CMSMcQ : make as many corrections as possible, from Terry Allen, Norbert Mikula, James Clark, Jon Bosak, Henry Thompson, Paul Grosso, and self. Among other things: give in on "well formed" (Terry is right), tentatively rename QuotedCData as AttValue and Literal as EntityValue to be more informative, since attribute values are the only place QuotedCData was used, and vice versa for entity text and Literal. (I'd call it Entity Text, but 8879 uses that name for both internal and external entities.) 1997-03-26 : CMSMcQ : resynch the two forks of this draft, reapply my changes dated 03-20 and 03-21. Normalize old 'may not' to 'must not' except in the one case where it meant 'may or may not'. 1997-03-21 : TB : massive changes on plane flight from Chicago to Vancouver 1997-03-21 : CMSMcQ : correct as many reported errors as possible. 1997-03-20 : CMSMcQ : correct typos listed in CMSMcQ hand copy of spec. 1997-03-20 : CMSMcQ : cosmetic changes preparatory to revision for WWW conference April 1997: restore some of the internal entity references (e.g. to docdate, etc.), change character xA0 to &nbsp; and define nbsp as &#160;, and refill a lot of paragraphs for legibility. 1996-11-12 : CMSMcQ : revise using Tim's edits: Add list type of NUMBERED and change most lists either to BULLETS or to NUMBERED. Suppress QuotedNames, Names (not used). Correct trivial-grammar doc type decl. Rename 'marked section' as 'CDATA section' passim. Also edits from James Clark: Define the set of characters from which [^abc] subtracts. Charref should use just [0-9] not Digit. Location info needs cleaner treatment: remove? (ERB question). One example of a PI has wrong pic. Clarify discussion of encoding names. Encoding failure should lead to unspecified results; don't prescribe error recovery. Don't require exposure of entity boundaries. Ignore white space in element content. Reserve entity names of the form u-NNNN. Clarify relative URLs. And some of my own: Correct productions for content model: model cannot consist of a name, so "elements ::= cp" is no good. 1996-11-11 : CMSMcQ : revise for style. Add new rhs to entity declaration, for parameter entities. 1996-11-10 : CMSMcQ : revise for style. Fix / complete section on names, characters. Add sections on parameter entities, conditional sections. Still to do: Add compatibility note on deterministic content models. Finish stylistic revision. 1996-10-31 : TB : Add Entity Handling section 1996-10-30 : TB : Clean up term & termdef. Slip in ERB decision re EMPTY. 1996-10-28 : TB : Change DTD. Implement some of Michael's suggestions. Change comments back to //. Introduce language for XML namespace reservation. Add section on white-space handling. Lots more cleanup. 1996-10-24 : CMSMcQ : quick tweaks, implement some ERB decisions. Characters are not integers. Comments are /* */ not //. Add bibliographic refs to 10646, HyTime, Unicode. Rename old Cdata as MsData since it's only seen in marked sections. Call them attribute-value pairs not name-value pairs, except once. Internal subset is optional, needs '?'. Implied attributes should be signaled to the app, not have values supplied by processor. 1996-10-16 : TB : track down & excise all DSD references; introduce some EBNF for entity declarations. 1996-10-?? : TB : consistency check, fix up scraps so they all parse, get formatter working, correct a few productions. 1996-10-10/11 : CMSMcQ : various maintenance, stylistic, and organizational changes: Replace a few literals with xmlpio and pic entities, to make them consistent and ensure we can change pic reliably when the ERB votes. Drop paragraph on recognizers from notation section. Add match, exact match to terminology. Move old 2.2 XML Processors and Apps into intro. Mention comments, PIs, and marked sections in discussion of delimiter escaping. Streamline discussion of doctype decl syntax. Drop old section of 'PI syntax' for doctype decl, and add section on partial-DTD summary PIs to end of Logical Structures section. Revise DSD syntax section to use Tim's subset-in-a-PI mechanism. 1996-10-10 : TB : eliminate name recognizers (and more?) 1996-10-09 : CMSMcQ : revise for style, consistency through 2.3 (Characters) 1996-10-09 : CMSMcQ : re-unite everything for convenience, at least temporarily, and revise quickly 1996-10-08 : TB : first major homogenization pass 1996-10-08 : TB : turn "current" attribute on div type into CDATA 1996-10-02 : TB : remould into skeleton + entities 1996-09-30 : CMSMcQ : add a few more sections prior to exchange with Tim. 1996-09-20 : CMSMcQ : finish transcribing notes. 1996-09-19 : CMSMcQ : begin transcribing notes for draft. 1996-09-13 : CMSMcQ : made outline from notes of 09-06, do some housekeeping
Introduction

Extensible Markup Language, abbreviated XML, describes a class of data objects called XML documents and partially describes the behavior of computer programs which process them. XML is an application profile or restricted form of SGML, the Standard Generalized Markup Language . By construction, XML documents are conforming SGML documents.

XML documents are made up of storage units called entities, which contain either parsed or unparsed data. Parsed data is made up of characters, some of which form character data, and some of which form markup. Markup encodes a description of the document's storage layout and logical structure. XML provides a mechanism to impose constraints on the storage layout and logical structure.

A software module called an XML processor is used to read XML documents and provide access to their content and structure. It is assumed that an XML processor is doing its work on behalf of another module, called the application. This specification describes the required behavior of an XML processor in terms of how it must read XML data and the information it must provide to the application.

Origin and Goals

XML was developed by an XML Working Group (originally known as the SGML Editorial Review Board) formed under the auspices of the World Wide Web Consortium (W3C) in 1996. It was chaired by Jon Bosak of Sun Microsystems with the active participation of an XML Special Interest Group (previously known as the SGML Working Group) also organized by the W3C. The membership of the XML Working Group is given in an appendix. Dan Connolly served as the WG's contact with the W3C.

The design goals for XML are:

XML shall be straightforwardly usable over the Internet.

XML shall support a wide variety of applications.

XML shall be compatible with SGML.

It shall be easy to write programs which process XML documents.

The number of optional features in XML is to be kept to the absolute minimum, ideally zero.

XML documents should be human-legible and reasonably clear.

The XML design should be prepared quickly.

The design of XML shall be formal and concise.

XML documents shall be easy to create.

Terseness in XML markup is of minimal importance.

This specification, together with associated standards (Unicode and ISO/IEC 10646 for characters, Internet RFC 1766 for language identification tags, ISO 639 for language name codes, and ISO 3166 for country name codes), provides all the information necessary to understand XML Version &XML.version; and construct computer programs to process it.

This version of the XML specification &doc.distribution;.

Terminology

The terminology used to describe XML documents is defined in the body of this specification. The terms defined in the following list are used in building those definitions and in describing the actions of an XML processor:

Conforming documents and XML processors are permitted to but need not behave as described.

Conforming documents and XML processors are required to behave as described; otherwise they are in error.

A violation of the rules of this specification; results are undefined. Conforming software may detect and report an error and may recover from it.

An error which a conforming XML processor must detect and report to the application. After encountering a fatal error, the processor may continue processing the data to search for further errors and may report such errors to the application. In order to support correction of errors, the processor may make unprocessed data from the document (with intermingled character data and markup) available to the application. Once a fatal error is detected, however, the processor must not continue normal processing (i.e., it must not continue to pass character data and information about the document's logical structure to the application in the normal way).

Conforming software may or must (depending on the modal verb in the sentence) behave as described; if it does, it must provide users a means to enable or disable the behavior described.

A rule which applies to all valid XML documents. Violations of validity constraints are errors; they must, at user option, be reported by validating XML processors.

A rule which applies to all well-formed XML documents. Violations of well-formedness constraints are fatal errors.

(Of strings or names:) Two strings or names being compared must be identical. Characters with multiple possible representations in ISO/IEC 10646 (e.g. characters with both precomposed and base+diacritic forms) match only if they have the same representation in both strings. At user option, processors may normalize such characters to some canonical form. No case folding is performed. (Of strings and rules in the grammar:) A string matches a grammatical production if it belongs to the language generated by that production. (Of content and content models:) An element matches its declaration when it conforms in the fashion described in the constraint .

A feature of XML included solely to ensure that XML remains compatible with SGML.

A non-binding recommendation included to increase the chances that XML documents can be processed by the existing installed base of SGML processors which predate the &WebSGML;.

Documents

A data object is an XML document if it is well-formed, as defined in this specification. A well-formed XML document may in addition be valid if it meets certain further constraints.

Each XML document has both a logical and a physical structure. Physically, the document is composed of units called entities. An entity may refer to other entities to cause their inclusion in the document. A document begins in a "root" or document entity. Logically, the document is composed of declarations, elements, comments, character references, and processing instructions, all of which are indicated in the document by explicit markup. The logical and physical structures must nest properly, as described in .

Well-Formed XML Documents

A textual object is a well-formed XML document if:

Taken as a whole, it matches the production labeled document.

It meets all the well-formedness constraints given in this specification.

Each of the parsed entities which is referenced directly or indirectly within the document is well-formed.

Document document prolog element Misc*

Matching the document production implies that:

It contains one or more elements.

There is exactly one element, called the root, or document element, no part of which appears in the content of any other element. For all other elements, if the start-tag is in the content of another element, the end-tag is in the content of the same element. More simply stated, the elements, delimited by start- and end-tags, nest properly within each other.

As a consequence of this, for each non-root element C in the document, there is one other element P in the document such that C is in the content of P, but is not in the content of any other element that is in the content of P. P is referred to as the parent of C, and C as a child of P.

Characters

A parsed entity contains text, a sequence of characters, which may represent markup or character data. A character is an atomic unit of text as specified by ISO/IEC 10646 . Legal characters are tab, carriage return, line feed, and the legal graphic characters of Unicode and ISO/IEC 10646. The use of "compatibility characters", as defined in section 6.8 of , is discouraged. Character Range Char #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.

The mechanism for encoding character code points into bit patterns may vary from entity to entity. All XML processors must accept the UTF-8 and UTF-16 encodings of 10646; the mechanisms for signaling which of the two is in use, or for bringing other encodings into play, are discussed later, in .

Common Syntactic Constructs

This section defines some symbols used widely in the grammar.

S (white space) consists of one or more space (#x20) characters, carriage returns, line feeds, or tabs. White Space S (#x20 | #x9 | #xD | #xA)+

Characters are classified for convenience as letters, digits, or other characters. Letters consist of an alphabetic or syllabic base character possibly followed by one or more combining characters, or of an ideographic character. Full definitions of the specific characters in each class are given in .

A Name is a token beginning with a letter or one of a few punctuation characters, and continuing with letters, digits, hyphens, underscores, colons, or full stops, together known as name characters. Names beginning with the string "xml", or any string which would match (('X'|'x') ('M'|'m') ('L'|'l')), are reserved for standardization in this or future versions of this specification.

The colon character within XML names is reserved for experimentation with name spaces. Its meaning is expected to be standardized at some future point, at which point those documents using the colon for experimental purposes may need to be updated. (There is no guarantee that any name-space mechanism adopted for XML will in fact use the colon as a name-space delimiter.) In practice, this means that authors should not use the colon in XML names except as part of name-space experiments, but that XML processors should accept the colon as a name character.

An Nmtoken (name token) is any mixture of name characters. Names and Tokens NameChar Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender Name (Letter | '_' | ':') (NameChar)* Names Name (S Name)* Nmtoken (NameChar)+ Nmtokens Nmtoken (S Nmtoken)*

Literal data is any quoted string not containing the quotation mark used as a delimiter for that string. Literals are used for specifying the content of internal entities (EntityValue), the values of attributes (AttValue), and external identifiers (SystemLiteral). Note that a SystemLiteral can be parsed without scanning for markup. Literals EntityValue '"' ([^%&"] | PEReference | Reference)* '"' |  "'" ([^%&'] | PEReference | Reference)* "'" AttValue '"' ([^<&"] | Reference)* '"' |  "'" ([^<&'] | Reference)* "'" SystemLiteral ('"' [^"]* '"') | ("'" [^']* "'") PubidLiteral '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" PubidChar #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]

Character Data and Markup

Text consists of intermingled character data and markup. Markup takes the form of start-tags, end-tags, empty-element tags, entity references, character references, comments, CDATA section delimiters, document type declarations, and processing instructions.

All text that is not markup constitutes the character data of the document.

The ampersand character (&) and the left angle bracket (<) may appear in their literal form only when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. They are also legal within the literal entity value of an internal entity declaration; see . If they are needed elsewhere, they must be escaped using either numeric character references or the strings "&amp;" and "&lt;" respectively. The right angle bracket (>) may be represented using the string "&gt;", and must, for compatibility, be escaped using "&gt;" or a character reference when it appears in the string "]]>" in content, when that string is not marking the end of a CDATA section.

In the content of elements, character data is any string of characters which does not contain the start-delimiter of any markup. In a CDATA section, character data is any string of characters not including the CDATA-section-close delimiter, "]]>".

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "&apos;", and the double-quote character (") as "&quot;". Character Data CharData [^<&]* - ([^<&]* ']]>' [^<&]*)

Comments

Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor may, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string "--" (double-hyphen) must not occur within comments. Comments Comment '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'

An example of a comment: <!&como; declarations for <head> & <body> &comc;>

Processing Instructions

Processing instructions (PIs) allow documents to contain instructions for applications. Processing Instructions PI '<?' PITarget (S (Char* - (Char* &pic; Char*)))? &pic; PITarget Name - (('X' | 'x') ('M' | 'm') ('L' | 'l')) PIs are not part of the document's character data, but must be passed through to the application. The PI begins with a target (PITarget) used to identify the application to which the instruction is directed. The target names "XML", "xml", and so on are reserved for standardization in this or future versions of this specification. The XML Notation mechanism may be used for formal declaration of PI targets.

CDATA Sections

CDATA sections may occur anywhere character data may occur; they are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string "<![CDATA[" and end with the string "]]>": CDATA Sections CDSect CDStart CData CDEnd CDStart '<![CDATA[' CData (Char* - (Char* ']]>' Char*)) CDEnd ']]>' Within a CDATA section, only the CDEnd string is recognized as markup, so that left angle brackets and ampersands may occur in their literal form; they need not (and cannot) be escaped using "&lt;" and "&amp;". CDATA sections cannot nest.

An example of a CDATA section, in which "<greeting>" and "</greeting>" are recognized as character data, not markup: <![CDATA[<greeting>Hello, world!</greeting>]]>

Prolog and Document Type Declaration

XML documents may, and should, begin with an XML declaration which specifies the version of XML being used. For example, the following is a complete XML document, well-formed but not valid: Hello, world! ]]> and so is this: Hello, world! ]]>

The version number "1.0" should be used to indicate conformance to this version of this specification; it is an error for a document to use the value "1.0" if it does not conform to this version of this specification. It is the intent of the XML working group to give later versions of this specification numbers other than "1.0", but this intent does not indicate a commitment to produce any future versions of XML, nor if any are produced, to use any particular numbering scheme. Since future versions are not ruled out, this construct is provided as a means to allow the possibility of automatic version recognition, should it become necessary. Processors may signal an error if they receive documents labeled with versions they do not support.

The function of the markup in an XML document is to describe its storage and logical structure and to associate attribute-value pairs with its logical structures. XML provides a mechanism, the document type declaration, to define constraints on the logical structure and to support the use of predefined storage units. An XML document is valid if it has an associated document type declaration and if the document complies with the constraints expressed in it.

The document type declaration must appear before the first element in the document. Prolog prolog XMLDecl? Misc* (doctypedecl Misc*)? XMLDecl &xmlpio; VersionInfo EncodingDecl? SDDecl? S? &pic; VersionInfo S 'version' Eq (' VersionNum ' | " VersionNum ") Eq S? '=' S? VersionNum ([a-zA-Z0-9_.:] | '-')+ Misc Comment | PI | S

The XML document type declaration contains or points to markup declarations that provide a grammar for a class of documents. This grammar is known as a document type definition, or DTD. The document type declaration can point to an external subset (a special kind of external entity) containing markup declarations, or can contain the markup declarations directly in an internal subset, or can do both. The DTD for a document consists of both subsets taken together.

A markup declaration is an element type declaration, an attribute-list declaration, an entity declaration, or a notation declaration. These declarations may be contained in whole or in part within parameter entities, as described in the well-formedness and validity constraints below. For fuller information, see .

Document Type Definition doctypedecl '<!DOCTYPE' S Name (S ExternalID)? S? ('[' (markupdecl | PEReference | S)* ']' S?)? '>' markupdecl elementdecl | AttlistDecl | EntityDecl | NotationDecl | PI | Comment

The markup declarations may be made up in whole or in part of the replacement text of parameter entities. The productions later in this specification for individual nonterminals (elementdecl, AttlistDecl, and so on) describe the declarations after all the parameter entities have been included.

Root Element Type

The Name in the document type declaration must match the element type of the root element.

Proper Declaration/PE Nesting

Parameter-entity replacement text must be properly nested with markup declarations. That is to say, if either the first character or the last character of a markup declaration (markupdecl above) is contained in the replacement text for a parameter-entity reference, both must be contained in the same replacement text.

PEs in Internal Subset

In the internal DTD subset, parameter-entity references can occur only where markup declarations can occur, not within markup declarations. (This does not apply to references that occur in external parameter entities or to the external subset.)

Like the internal subset, the external subset and any external parameter entities referred to in the DTD must consist of a series of complete markup declarations of the types allowed by the non-terminal symbol markupdecl, interspersed with white space or parameter-entity references. However, portions of the contents of the external subset or of external parameter entities may conditionally be ignored by using the conditional section construct; this is not allowed in the internal subset. External Subset extSubset TextDecl? extSubsetDecl extSubsetDecl ( markupdecl | conditionalSect | PEReference | S )*

The external subset and external parameter entities also differ from the internal subset in that in them, parameter-entity references are permitted within markup declarations, not only between markup declarations.

An example of an XML document with a document type declaration: Hello, world! ]]> The system identifier "hello.dtd" gives the URI of a DTD for the document.

The declarations can also be given locally, as in this example: ]> Hello, world! ]]> If both the external and internal subsets are used, the internal subset is considered to occur before the external subset. This has the effect that entity and attribute-list declarations in the internal subset take precedence over those in the external subset.

Standalone Document Declaration

Markup declarations can affect the content of the document, as passed from an XML processor to an application; examples are attribute defaults and entity declarations. The standalone document declaration, which may appear as a component of the XML declaration, signals whether or not there are such declarations which appear external to the document entity. Standalone Document Declaration SDDecl S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"'))

In a standalone document declaration, the value "yes" indicates that there are no markup declarations external to the document entity (either in the DTD external subset, or in an external parameter entity referenced from the internal subset) which affect the information passed from the XML processor to the application. The value "no" indicates that there are or may be such external markup declarations. Note that the standalone document declaration only denotes the presence of external declarations; the presence, in a document, of references to external entities, when those entities are internally declared, does not change its standalone status.

If there are no external markup declarations, the standalone document declaration has no meaning. If there are external markup declarations but there is no standalone document declaration, the value "no" is assumed.

Any XML document for which standalone="no" holds can be converted algorithmically to a standalone document, which may be desirable for some network delivery applications.

Standalone Document Declaration

The standalone document declaration must have the value "no" if any external markup declarations contain declarations of:

attributes with default values, if elements to which these attributes apply appear in the document without specifications of values for these attributes, or

entities (other than &magicents;), if references to those entities appear in the document, or

attributes with values subject to normalization, where the attribute appears in the document with a value which will change as a result of normalization, or

element types with element content, if white space occurs directly within any instance of those types.

An example XML declaration with a standalone document declaration:<?xml version="&XML.version;" standalone='yes'?>

White Space Handling

In editing XML documents, it is often convenient to use "white space" (spaces, tabs, and blank lines, denoted by the nonterminal S in this specification) to set apart the markup for greater readability. Such white space is typically not intended for inclusion in the delivered version of the document. On the other hand, "significant" white space that should be preserved in the delivered version is common, for example in poetry and source code.

An XML processor must always pass all characters in a document that are not markup through to the application. A validating XML processor must also inform the application which of these characters constitute white space appearing in element content.

A special attribute named xml:space may be attached to an element to signal an intention that in that element, white space should be preserved by applications. In valid documents, this attribute, like any other, must be declared if it is used. When declared, it must be given as an enumerated type whose only possible values are "default" and "preserve". For example:]]>

The value "default" signals that applications' default white-space processing modes are acceptable for this element; the value "preserve" indicates the intent that applications preserve all the white space. This declared intent is considered to apply to all elements within the content of the element where it is specified, unless overriden with another instance of the xml:space attribute.

The root element of any document is considered to have signaled no intentions as regards application space handling, unless it provides a value for this attribute or the attribute is declared with a default value.

End-of-Line Handling

XML parsed entities are often stored in computer files which, for editing convenience, are organized into lines. These lines are typically separated by some combination of the characters carriage-return (#xD) and line-feed (#xA).

To simplify the tasks of applications, wherever an external parsed entity or the literal entity value of an internal parsed entity contains either the literal two-character sequence "#xD#xA" or a standalone literal #xD, an XML processor must pass to the application the single character #xA. (This behavior can conveniently be produced by normalizing all line breaks to #xA on input, before parsing.)

Language Identification

In document processing, it is often useful to identify the natural or formal language in which the content is written. A special attribute named xml:lang may be inserted in documents to specify the language used in the contents and attribute values of any element in an XML document. In valid documents, this attribute, like any other, must be declared if it is used. The values of the attribute are language identifiers as defined by , "Tags for the Identification of Languages": Language Identification LanguageID Langcode ('-' Subcode)* Langcode ISO639Code | IanaCode | UserCode ISO639Code ([a-z] | [A-Z]) ([a-z] | [A-Z]) IanaCode ('i' | 'I') '-' ([a-z] | [A-Z])+ UserCode ('x' | 'X') '-' ([a-z] | [A-Z])+ Subcode ([a-z] | [A-Z])+ The Langcode may be any of the following:

a two-letter language code as defined by , "Codes for the representation of names of languages"

a language identifier registered with the Internet Assigned Numbers Authority ; these begin with the prefix "i-" (or "I-")

a language identifier assigned by the user, or agreed on between parties in private use; these must begin with the prefix "x-" or "X-" in order to ensure that they do not conflict with names later standardized or registered with IANA

There may be any number of Subcode segments; if the first subcode segment exists and the Subcode consists of two letters, then it must be a country code from , "Codes for the representation of names of countries." If the first subcode consists of more than two letters, it must be a subcode for the language in question registered with IANA, unless the Langcode begins with the prefix "x-" or "X-".

It is customary to give the language code in lower case, and the country code (if any) in upper case. Note that these values, unlike other names in XML documents, are case insensitive.

For example: The quick brown fox jumps over the lazy dog.

What colour is it?

What color is it?

Habe nun, ach! Philosophie, Juristerei, und Medizin und leider auch Theologie durchaus studiert mit heißem Bemüh'n. ]]>

The intent declared with xml:lang is considered to apply to all attributes and content of the element where it is specified, unless overridden with an instance of xml:lang on another element within that content.

A simple declaration for xml:lang might take the form xml:lang NMTOKEN #IMPLIED but specific default values may also be given, if appropriate. In a collection of French poems for English students, with glosses and notes in English, the xml:lang attribute might be declared this way: ]]>

Logical Structures

Each XML document contains one or more elements, the boundaries of which are either delimited by start-tags and end-tags, or, for empty elements, by an empty-element tag. Each element has a type, identified by name, sometimes called its "generic identifier" (GI), and may have a set of attribute specifications. Each attribute specification has a name and a value.

Element element EmptyElemTag | STag content ETag

This specification does not constrain the semantics, use, or (beyond syntax) names of the element types and attributes, except that names beginning with a match to (('X'|'x')('M'|'m')('L'|'l')) are reserved for standardization in this or future versions of this specification.

Element Type Match

The Name in an element's end-tag must match the element type in the start-tag.

Element Valid

An element is valid if there is a declaration matching elementdecl where the Name matches the element type, and one of the following holds:

The declaration matches EMPTY and the element has no content.

The declaration matches children and the sequence of child elements belongs to the language generated by the regular expression in the content model, with optional white space (characters matching the nonterminal S) between each pair of child elements.

The declaration matches Mixed and the content consists of character data and child elements whose types match names in the content model.

The declaration matches ANY, and the types of any child elements have been declared.

Start-Tags, End-Tags, and Empty-Element Tags

The beginning of every non-empty XML element is marked by a start-tag. Start-tag STag '<' Name (S Attribute)* S? '>' Attribute Name Eq AttValue The Name in the start- and end-tags gives the element's type. The Name-AttValue pairs are referred to as the attribute specifications of the element, with the Name in each pair referred to as the attribute name and the content of the AttValue (the text between the ' or " delimiters) as the attribute value.

Unique Att Spec

No attribute name may appear more than once in the same start-tag or empty-element tag.

Attribute Value Type

The attribute must have been declared; the value must be of the type declared for it. (For attribute types, see .)

No External Entity References

Attribute values cannot contain direct or indirect entity references to external entities.

No < in Attribute Values

The replacement text of any entity referred to directly or indirectly in an attribute value (other than "&lt;") must not contain a <.

An example of a start-tag: <termdef id="dt-dog" term="dog">

The end of every element that begins with a start-tag must be marked by an end-tag containing a name that echoes the element's type as given in the start-tag: End-tag ETag '</' Name S? '>'

An example of an end-tag:</termdef>

The text between the start-tag and end-tag is called the element's content: Content of Elements content (element | CharData | Reference | CDSect | PI | Comment)*

If an element is empty, it must be represented either by a start-tag immediately followed by an end-tag or by an empty-element tag. An empty-element tag takes a special form: Tags for Empty Elements EmptyElemTag '<' Name (S Attribute)* S? '/>'

Empty-element tags may be used for any element which has no content, whether or not it is declared using the keyword EMPTY. For interoperability, the empty-element tag must be used, and can only be used, for elements which are declared EMPTY.

Examples of empty elements: <IMG align="left" src="http://www.w3.org/Icons/WWW/w3c_home" /> <br></br> <br/>

Element Type Declarations

The element structure of an XML document may, for validation purposes, be constrained using element type and attribute-list declarations. An element type declaration constrains the element's content.

Element type declarations often constrain which element types can appear as children of the element. At user option, an XML processor may issue a warning when a declaration mentions an element type for which no declaration is provided, but this is not an error.

An element type declaration takes the form: Element Type Declaration elementdecl '<!ELEMENT' S Name S contentspec S? '>' contentspec 'EMPTY' | 'ANY' | Mixed | children where the Name gives the element type being declared.

Unique Element Type Declaration

No element type may be declared more than once.

Examples of element type declarations: <!ELEMENT br EMPTY> <!ELEMENT p (#PCDATA|emph)* > <!ELEMENT %name.para; %content.para; > <!ELEMENT container ANY>

Element Content

An element type has element content when elements of that type must contain only child elements (no character data), optionally separated by white space (characters matching the nonterminal S). In this case, the constraint includes a content model, a simple grammar governing the allowed types of the child elements and the order in which they are allowed to appear. The grammar is built on content particles (cps), which consist of names, choice lists of content particles, or sequence lists of content particles: Element-content Models children (choice | seq) ('?' | '*' | '+')? cp (Name | choice | seq) ('?' | '*' | '+')? choice '(' S? cp ( S? '|' S? cp )* S? ')' seq '(' S? cp ( S? ',' S? cp )* S? ')' where each Name is the type of an element which may appear as a child. Any content particle in a choice list may appear in the element content at the location where the choice list appears in the grammar; content particles occurring in a sequence list must each appear in the element content in the order given in the list. The optional character following a name or list governs whether the element or the content particles in the list may occur one or more (+), zero or more (*), or zero or one times (?). The absence of such an operator means that the element or content particle must appear exactly once. This syntax and meaning are identical to those used in the productions in this specification.

The content of an element matches a content model if and only if it is possible to trace out a path through the content model, obeying the sequence, choice, and repetition operators and matching each element in the content against an element type in the content model. For compatibility, it is an error if an element in the document can match more than one occurrence of an element type in the content model. For more information, see .

Proper Group/PE Nesting

Parameter-entity replacement text must be properly nested with parenthetized groups. That is to say, if either of the opening or closing parentheses in a choice, seq, or Mixed construct is contained in the replacement text for a parameter entity, both must be contained in the same replacement text.

For interoperability, if a parameter-entity reference appears in a choice, seq, or Mixed construct, its replacement text should not be empty, and neither the first nor last non-blank character of the replacement text should be a connector (| or ,).

Examples of element-content models: <!ELEMENT spec (front, body, back?)> <!ELEMENT div1 (head, (p | list | note)*, div2*)> <!ELEMENT dictionary-body (%div.mix; | %dict.mix;)*>

Mixed Content

An element type has mixed content when elements of that type may contain character data, optionally interspersed with child elements. In this case, the types of the child elements may be constrained, but not their order or their number of occurrences: Mixed-content Declaration Mixed '(' S? '#PCDATA' (S? '|' S? Name)* S? ')*' | '(' S? '#PCDATA' S? ')' where the Names give the types of elements that may appear as children.

No Duplicate Types

The same name must not appear more than once in a single mixed-content declaration.

Examples of mixed content declarations: <!ELEMENT p (#PCDATA|a|ul|b|i|em)*> <!ELEMENT p (#PCDATA | %font; | %phrase; | %special; | %form;)* > <!ELEMENT b (#PCDATA)>

Attribute-List Declarations

Attributes are used to associate name-value pairs with elements. Attribute specifications may appear only within start-tags and empty-element tags; thus, the productions used to recognize them appear in . Attribute-list declarations may be used:

To define the set of attributes pertaining to a given element type.

To establish type constraints for these attributes.

To provide default values for attributes.

Attribute-list declarations specify the name, data type, and default value (if any) of each attribute associated with a given element type: Attribute-list Declaration AttlistDecl '<!ATTLIST' S Name AttDef* S? '>' AttDef S Name S AttType S DefaultDecl The Name in the AttlistDecl rule is the type of an element. At user option, an XML processor may issue a warning if attributes are declared for an element type not itself declared, but this is not an error. The Name in the AttDef rule is the name of the attribute.

When more than one AttlistDecl is provided for a given element type, the contents of all those provided are merged. When more than one definition is provided for the same attribute of a given element type, the first declaration is binding and later declarations are ignored. For interoperability, writers of DTDs may choose to provide at most one attribute-list declaration for a given element type, at most one attribute definition for a given attribute name, and at least one attribute definition in each attribute-list declaration. For interoperability, an XML processor may at user option issue a warning when more than one attribute-list declaration is provided for a given element type, or more than one attribute definition is provided for a given attribute, but this is not an error.

Attribute Types

XML attribute types are of three kinds: a string type, a set of tokenized types, and enumerated types. The string type may take any literal string as a value; the tokenized types have varying lexical and semantic constraints, as noted: Attribute Types AttType StringType | TokenizedType | EnumeratedType StringType 'CDATA' TokenizedType 'ID' | 'IDREF' | 'IDREFS' | 'ENTITY' | 'ENTITIES' | 'NMTOKEN' | 'NMTOKENS'

ID

Values of type ID must match the Name production. A name must not appear more than once in an XML document as a value of this type; i.e., ID values must uniquely identify the elements which bear them.

One ID per Element Type

No element type may have more than one ID attribute specified.

ID Attribute Default

An ID attribute must have a declared default of #IMPLIED or #REQUIRED.

IDREF

Values of type IDREF must match the Name production, and values of type IDREFS must match Names; each Name must match the value of an ID attribute on some element in the XML document; i.e. IDREF values must match the value of some ID attribute.

Entity Name

Values of type ENTITY must match the Name production, values of type ENTITIES must match Names; each Name must match the name of an unparsed entity declared in the DTD.

Name Token

Values of type NMTOKEN must match the Nmtoken production; values of type NMTOKENS must match Nmtokens.

Enumerated attributes can take one of a list of values provided in the declaration. There are two kinds of enumerated types: Enumerated Attribute Types EnumeratedType NotationType | Enumeration NotationType 'NOTATION' S '(' S? Name (S? '|' S? Name)* S? ')' Enumeration '(' S? Nmtoken (S? '|' S? Nmtoken)* S? ')' A NOTATION attribute identifies a notation, declared in the DTD with associated system and/or public identifiers, to be used in interpreting the element to which the attribute is attached.

Notation Attributes

Values of this type must match one of the notation names included in the declaration; all notation names in the declaration must be declared.

Enumeration

Values of this type must match one of the Nmtoken tokens in the declaration.

For interoperability, the same Nmtoken should not occur more than once in the enumerated attribute types of a single element type.

Attribute Defaults

An attribute declaration provides information on whether the attribute's presence is required, and if not, how an XML processor should react if a declared attribute is absent in a document. Attribute Defaults DefaultDecl '#REQUIRED' | '#IMPLIED' | (('#FIXED' S)? AttValue)

In an attribute declaration, #REQUIRED means that the attribute must always be provided, #IMPLIED that no default value is provided. If the declaration is neither #REQUIRED nor #IMPLIED, then the AttValue value contains the declared default value; the #FIXED keyword states that the attribute must always have the default value. If a default value is declared, when an XML processor encounters an omitted attribute, it is to behave as though the attribute were present with the declared default value.

Required Attribute

If the default declaration is the keyword #REQUIRED, then the attribute must be specified for all elements of the type in the attribute-list declaration.

Attribute Default Legal

The declared default value must meet the lexical constraints of the declared attribute type.

Fixed Attribute Default

If an attribute has a default value declared with the #FIXED keyword, instances of that attribute must match the default value.

Examples of attribute-list declarations: <!ATTLIST termdef id ID #REQUIRED name CDATA #IMPLIED> <!ATTLIST list type (bullets|ordered|glossary) "ordered"> <!ATTLIST form method CDATA #FIXED "POST">

Attribute-Value Normalization

Before the value of an attribute is passed to the application or checked for validity, the XML processor must normalize it as follows:

a character reference is processed by appending the referenced character to the attribute value

an entity reference is processed by recursively processing the replacement text of the entity

a whitespace character (#x20, #xD, #xA, #x9) is processed by appending #x20 to the normalized value, except that only a single #x20 is appended for a "#xD#xA" sequence that is part of an external parsed entity or the literal entity value of an internal parsed entity

other characters are processed by appending them to the normalized value

If the declared value is not CDATA, then the XML processor must further process the normalized attribute value by discarding any leading and trailing space (#x20) characters, and by replacing sequences of space (#x20) characters by a single space (#x20) character.

All attributes for which no declaration has been read should be treated by a non-validating parser as if declared CDATA.

Conditional Sections

Conditional sections are portions of the document type declaration external subset which are included in, or excluded from, the logical structure of the DTD based on the keyword which governs them. Conditional Section conditionalSect includeSect | ignoreSect includeSect '<![' S? 'INCLUDE' S? '[' extSubsetDecl ']]>' ignoreSect '<![' S? 'IGNORE' S? '[' ignoreSectContents* ']]>' ignoreSectContents Ignore ('<![' ignoreSectContents ']]>' Ignore)* Ignore Char* - (Char* ('<![' | ']]>') Char*)

Like the internal and external DTD subsets, a conditional section may contain one or more complete declarations, comments, processing instructions, or nested conditional sections, intermingled with white space.

If the keyword of the conditional section is INCLUDE, then the contents of the conditional section are part of the DTD. If the keyword of the conditional section is IGNORE, then the contents of the conditional section are not logically part of the DTD. Note that for reliable parsing, the contents of even ignored conditional sections must be read in order to detect nested conditional sections and ensure that the end of the outermost (ignored) conditional section is properly detected. If a conditional section with a keyword of INCLUDE occurs within a larger conditional section with a keyword of IGNORE, both the outer and the inner conditional sections are ignored.

If the keyword of the conditional section is a parameter-entity reference, the parameter entity must be replaced by its content before the processor decides whether to include or ignore the conditional section.

An example: <!ENTITY % draft 'INCLUDE' > <!ENTITY % final 'IGNORE' > <![%draft;[ <!ELEMENT book (comments*, title, body, supplements?)> ]]> <![%final;[ <!ELEMENT book (title, body, supplements?)> ]]>

Physical Structures

An XML document may consist of one or many storage units. These are called entities; they all have content and are all (except for the document entity, see below, and the external DTD subset) identified by name. Each XML document has one entity called the document entity, which serves as the starting point for the XML processor and may contain the whole document.

Entities may be either parsed or unparsed. A parsed entity's contents are referred to as its replacement text; this text is considered an integral part of the document.

An unparsed entity is a resource whose contents may or may not be text, and if text, may not be XML. Each unparsed entity has an associated notation, identified by name. Beyond a requirement that an XML processor make the identifiers for the entity and notation available to the application, XML places no constraints on the contents of unparsed entities.

Parsed entities are invoked by name using entity references; unparsed entities by name, given in the value of ENTITY or ENTITIES attributes.

General entities are entities for use within the document content. In this specification, general entities are sometimes referred to with the unqualified term entity when this leads to no ambiguity. Parameter entities are parsed entities for use within the DTD. These two types of entities use different forms of reference and are recognized in different contexts. Furthermore, they occupy different namespaces; a parameter entity and a general entity with the same name are two distinct entities.

Character and Entity References

A character reference refers to a specific character in the ISO/IEC 10646 character set, for example one not directly accessible from available input devices. Character Reference CharRef '&#' [0-9]+ ';' | '&hcro;' [0-9a-fA-F]+ ';' Legal Character

Characters referred to using character references must match the production for Char.

If the character reference begins with "&#x", the digits and letters up to the terminating ; provide a hexadecimal representation of the character's code point in ISO/IEC 10646. If it begins just with "&#", the digits up to the terminating ; provide a decimal representation of the character's code point.

An entity reference refers to the content of a named entity. References to parsed general entities use ampersand (&) and semicolon (;) as delimiters. Parameter-entity references use percent-sign (%) and semicolon (;) as delimiters.

Entity Reference Reference EntityRef | CharRef EntityRef '&' Name ';' PEReference '%' Name ';' Entity Declared

In a document without any DTD, a document with only an internal DTD subset which contains no parameter entity references, or a document with "standalone='yes'", the Name given in the entity reference must match that in an entity declaration, except that well-formed documents need not declare any of the following entities: &magicents;. The declaration of a parameter entity must precede any reference to it. Similarly, the declaration of a general entity must precede any reference to it which appears in a default value in an attribute-list declaration.

Note that if entities are declared in the external subset or in external parameter entities, a non-validating processor is not obligated to read and process their declarations; for such documents, the rule that an entity must be declared is a well-formedness constraint only if standalone='yes'.

Entity Declared

In a document with an external subset or external parameter entities with "standalone='no'", the Name given in the entity reference must match that in an entity declaration. For interoperability, valid documents should declare the entities &magicents;, in the form specified in . The declaration of a parameter entity must precede any reference to it. Similarly, the declaration of a general entity must precede any reference to it which appears in a default value in an attribute-list declaration.

Parsed Entity

An entity reference must not contain the name of an unparsed entity. Unparsed entities may be referred to only in attribute values declared to be of type ENTITY or ENTITIES.

No Recursion

A parsed entity must not contain a recursive reference to itself, either directly or indirectly.

In DTD

Parameter-entity references may only appear in the DTD.

Examples of character and entity references: Type <key>less-than</key> (&hcro;3C;) to save options. This document was prepared on &docdate; and is classified &security-level;.

Example of a parameter-entity reference: %ISOLat2;]]>

Entity Declarations

Entities are declared thus: Entity Declaration EntityDecl GEDecl | PEDecl GEDecl '<!ENTITY' S Name S EntityDef S? '>' PEDecl '<!ENTITY' S '%' S Name S PEDef S? '>' EntityDef EntityValue | (ExternalID NDataDecl?) PEDef EntityValue | ExternalID The Name identifies the entity in an entity reference or, in the case of an unparsed entity, in the value of an ENTITY or ENTITIES attribute. If the same entity is declared more than once, the first declaration encountered is binding; at user option, an XML processor may issue a warning if entities are declared multiple times.

Internal Entities

If the entity definition is an EntityValue, the defined entity is called an internal entity. There is no separate physical storage object, and the content of the entity is given in the declaration. Note that some processing of entity and character references in the literal entity value may be required to produce the correct replacement text: see .

An internal entity is a parsed entity.

Example of an internal entity declaration: <!ENTITY Pub-Status "This is a pre-release of the specification.">

External Entities

If the entity is not internal, it is an external entity, declared as follows: External Entity Declaration ExternalID 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral NDataDecl S 'NDATA' S Name If the NDataDecl is present, this is a general unparsed entity; otherwise it is a parsed entity.

Notation Declared

The Name must match the declared name of a notation.

The SystemLiteral is called the entity's system identifier. It is a URI, which may be used to retrieve the entity. Note that the hash mark (#) and fragment identifier frequently used with URIs are not, formally, part of the URI itself; an XML processor may signal an error if a fragment identifier is given as part of a system identifier. Unless otherwise provided by information outside the scope of this specification (e.g. a special XML element type defined by a particular DTD, or a processing instruction defined by a particular application specification), relative URIs are relative to the location of the resource within which the entity declaration occurs. A URI might thus be relative to the document entity, to the entity containing the external DTD subset, or to some other external parameter entity.

An XML processor should handle a non-ASCII character in a URI by representing the character in UTF-8 as one or more bytes, and then escaping these bytes with the URI escaping mechanism (i.e., by converting each byte to %HH, where HH is the hexadecimal notation of the byte value).

In addition to a system identifier, an external identifier may include a public identifier. An XML processor attempting to retrieve the entity's content may use the public identifier to try to generate an alternative URI. If the processor is unable to do so, it must use the URI specified in the system literal. Before a match is attempted, all strings of white space in the public identifier must be normalized to single space characters (#x20), and leading and trailing white space must be removed.

Examples of external entity declarations: <!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml"> <!ENTITY open-hatch PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" "http://www.textuality.com/boilerplate/OpenHatch.xml"> <!ENTITY hatch-pic SYSTEM "../grafix/OpenHatch.gif" NDATA gif >

Parsed Entities The Text Declaration

External parsed entities may each begin with a text declaration. Text Declaration TextDecl &xmlpio; VersionInfo? EncodingDecl S? &pic;

The text declaration must be provided literally, not by reference to a parsed entity. No text declaration may appear at any position other than the beginning of an external parsed entity.

Well-Formed Parsed Entities

The document entity is well-formed if it matches the production labeled document. An external general parsed entity is well-formed if it matches the production labeled extParsedEnt. An external parameter entity is well-formed if it matches the production labeled extPE. Well-Formed External Parsed Entity extParsedEnt TextDecl? content extPE TextDecl? extSubsetDecl An internal general parsed entity is well-formed if its replacement text matches the production labeled content. All internal parameter entities are well-formed by definition.

A consequence of well-formedness in entities is that the logical and physical structures in an XML document are properly nested; no start-tag, end-tag, empty-element tag, element, comment, processing instruction, character reference, or entity reference can begin in one entity and end in another.

Character Encoding in Entities

Each external parsed entity in an XML document may use a different encoding for its characters. All XML processors must be able to read entities in either UTF-8 or UTF-16.

Entities encoded in UTF-16 must begin with the Byte Order Mark described by ISO/IEC 10646 Annex E and Unicode Appendix B (the ZERO WIDTH NO-BREAK SPACE character, #xFEFF). This is an encoding signature, not part of either the markup or the character data of the XML document. XML processors must be able to use this character to differentiate between UTF-8 and UTF-16 encoded documents.

Although an XML processor is required to read only entities in the UTF-8 and UTF-16 encodings, it is recognized that other encodings are used around the world, and it may be desired for XML processors to read entities that use them. Parsed entities which are stored in an encoding other than UTF-8 or UTF-16 must begin with a text declaration containing an encoding declaration: Encoding Declaration EncodingDecl S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" ) EncName [A-Za-z] ([A-Za-z0-9._] | '-')* Encoding name contains only Latin characters In the document entity, the encoding declaration is part of the XML declaration. The EncName is the name of the encoding used.

In an encoding declaration, the values "UTF-8", "UTF-16", "ISO-10646-UCS-2", and "ISO-10646-UCS-4" should be used for the various encodings and transformations of Unicode / ISO/IEC 10646, the values "ISO-8859-1", "ISO-8859-2", ... "ISO-8859-9" should be used for the parts of ISO 8859, and the values "ISO-2022-JP", "Shift_JIS", and "EUC-JP" should be used for the various encoded forms of JIS X-0208-1997. XML processors may recognize other encodings; it is recommended that character encodings registered (as charsets) with the Internet Assigned Numbers Authority , other than those just listed, should be referred to using their registered names. Note that these registered names are defined to be case-insensitive, so processors wishing to match against them should do so in a case-insensitive way.

In the absence of information provided by an external transport protocol (e.g. HTTP or MIME), it is an error for an entity including an encoding declaration to be presented to the XML processor in an encoding other than that named in the declaration, for an encoding declaration to occur other than at the beginning of an external entity, or for an entity which begins with neither a Byte Order Mark nor an encoding declaration to use an encoding other than UTF-8. Note that since ASCII is a subset of UTF-8, ordinary ASCII entities do not strictly need an encoding declaration.

It is a fatal error when an XML processor encounters an entity with an encoding that it is unable to process.

Examples of encoding declarations: <?xml encoding='UTF-8'?> <?xml encoding='EUC-JP'?>

XML Processor Treatment of Entities and References

The table below summarizes the contexts in which character references, entity references, and invocations of unparsed entities might appear and the required behavior of an XML processor in each case. The labels in the leftmost column describe the recognition context:

as a reference anywhere after the start-tag and before the end-tag of an element; corresponds to the nonterminal content.

as a reference within either the value of an attribute in a start-tag, or a default value in an attribute declaration; corresponds to the nonterminal AttValue.

as a Name, not a reference, appearing either as the value of an attribute which has been declared as type ENTITY, or as one of the space-separated tokens in the value of an attribute which has been declared as type ENTITIES.

as a reference within a parameter or internal entity's literal entity value in the entity's declaration; corresponds to the nonterminal EntityValue.

as a reference within either the internal or external subsets of the DTD, but outside of an EntityValue or AttValue.

Entity Type Character Parameter Internal General External Parsed General Unparsed Reference in Content Not recognized Included Included if validating Forbidden Included Reference in Attribute Value Not recognized Included in literal Forbidden Forbidden Included Occurs as Attribute Value Not recognized Forbidden Forbidden Notify Not recognized Reference in EntityValue Included in literal Bypassed Bypassed Forbidden Included Reference in DTD Included as PE Forbidden Forbidden Forbidden Forbidden Not Recognized

Outside the DTD, the % character has no special significance; thus, what would be parameter entity references in the DTD are not recognized as markup in content. Similarly, the names of unparsed entities are not recognized except when they appear in the value of an appropriately declared attribute.

Included

An entity is included when its replacement text is retrieved and processed, in place of the reference itself, as though it were part of the document at the location the reference was recognized. The replacement text may contain both character data and (except for parameter entities) markup, which must be recognized in the usual way, except that the replacement text of entities used to escape markup delimiters (the entities &magicents;) is always treated as data. (The string "AT&amp;T;" expands to "AT&T;" and the remaining ampersand is not recognized as an entity-reference delimiter.) A character reference is included when the indicated character is processed in place of the reference itself.

Included If Validating

When an XML processor recognizes a reference to a parsed entity, in order to validate the document, the processor must include its replacement text. If the entity is external, and the processor is not attempting to validate the XML document, the processor may, but need not, include the entity's replacement text. If a non-validating parser does not include the replacement text, it must inform the application that it recognized, but did not read, the entity.

This rule is based on the recognition that the automatic inclusion provided by the SGML and XML entity mechanism, primarily designed to support modularity in authoring, is not necessarily appropriate for other applications, in particular document browsing. Browsers, for example, when encountering an external parsed entity reference, might choose to provide a visual indication of the entity's presence and retrieve it for display only on demand.

Forbidden

The following are forbidden, and constitute fatal errors:

the appearance of a reference to an unparsed entity.

the appearance of any character or general-entity reference in the DTD except within an EntityValue or AttValue.

a reference to an external entity in an attribute value.

Included in Literal

When an entity reference appears in an attribute value, or a parameter entity reference appears in a literal entity value, its replacement text is processed in place of the reference itself as though it were part of the document at the location the reference was recognized, except that a single or double quote character in the replacement text is always treated as a normal data character and will not terminate the literal. For example, this is well-formed: ]]> while this is not: <!ENTITY EndAttr "27'" > <element attribute='a-&EndAttr;>

Notify

When the name of an unparsed entity appears as a token in the value of an attribute of declared type ENTITY or ENTITIES, a validating processor must inform the application of the system and public (if any) identifiers for both the entity and its associated notation.

Bypassed

When a general entity reference appears in the EntityValue in an entity declaration, it is bypassed and left as is.

Included as PE

Just as with external parsed entities, parameter entities need only be included if validating. When a parameter-entity reference is recognized in the DTD and included, its replacement text is enlarged by the attachment of one leading and one following space (#x20) character; the intent is to constrain the replacement text of parameter entities to contain an integral number of grammatical tokens in the DTD.

Construction of Internal Entity Replacement Text

In discussing the treatment of internal entities, it is useful to distinguish two forms of the entity's value. The literal entity value is the quoted string actually present in the entity declaration, corresponding to the non-terminal EntityValue. The replacement text is the content of the entity, after replacement of character references and parameter-entity references.

The literal entity value as given in an internal entity declaration (EntityValue) may contain character, parameter-entity, and general-entity references. Such references must be contained entirely within the literal entity value. The actual replacement text that is included as described above must contain the replacement text of any parameter entities referred to, and must contain the character referred to, in place of any character references in the literal entity value; however, general-entity references must be left as-is, unexpanded. For example, given the following declarations: ]]> then the replacement text for the entity "book" is: La Peste: Albert Camus, © 1947 Éditions Gallimard. &rights; The general-entity reference "&rights;" would be expanded should the reference "&book;" appear in the document's content or an attribute value.

These simple rules may have complex interactions; for a detailed discussion of a difficult example, see .

Predefined Entities

Entity and character references can both be used to escape the left angle bracket, ampersand, and other delimiters. A set of general entities (&magicents;) is specified for this purpose. Numeric character references may also be used; they are expanded immediately when recognized and must be treated as character data, so the numeric character references "&#60;" and "&#38;" may be used to escape < and & when they occur in character data.

All XML processors must recognize these entities whether they are declared or not. For interoperability, valid XML documents should declare these entities, like any others, before using them. If the entities in question are declared, they must be declared as internal entities whose replacement text is the single character being escaped or a character reference to that character, as shown below. ]]> Note that the < and & characters in the declarations of "lt" and "amp" are doubly escaped to meet the requirement that entity replacement be well-formed.

Notation Declarations

Notations identify by name the format of unparsed entities, the format of elements which bear a notation attribute, or the application to which a processing instruction is addressed.

Notation declarations provide a name for the notation, for use in entity and attribute-list declarations and in attribute specifications, and an external identifier for the notation which may allow an XML processor or its client application to locate a helper application capable of processing data in the given notation. Notation Declarations NotationDecl '<!NOTATION' S Name S (ExternalID | PublicID) S? '>' PublicID 'PUBLIC' S PubidLiteral

XML processors must provide applications with the name and external identifier(s) of any notation declared and referred to in an attribute value, attribute definition, or entity declaration. They may additionally resolve the external identifier into the system identifier, file name, or other information needed to allow the application to call a processor for data in the notation described. (It is not an error, however, for XML documents to declare and refer to notations for which notation-specific applications are not available on the system where the XML processor or application is running.)

Document Entity

The document entity serves as the root of the entity tree and a starting-point for an XML processor. This specification does not specify how the document entity is to be located by an XML processor; unlike other entities, the document entity has no name and might well appear on a processor input stream without any identification at all.

Conformance Validating and Non-Validating Processors

Conforming XML processors fall into two classes: validating and non-validating.

Validating and non-validating processors alike must report violations of this specification's well-formedness constraints in the content of the document entity and any other parsed entities that they read.

Validating processors must report violations of the constraints expressed by the declarations in the DTD, and failures to fulfill the validity constraints given in this specification. To accomplish this, validating XML processors must read and process the entire DTD and all external parsed entities referenced in the document.

Non-validating processors are required to check only the document entity, including the entire internal DTD subset, for well-formedness. While they are not required to check the document for validity, they are required to process all the declarations they read in the internal DTD subset and in any parameter entity that they read, up to the first reference to a parameter entity that they do not read; that is to say, they must use the information in those declarations to normalize attribute values, include the replacement text of internal entities, and supply default attribute values. They must not process entity declarations or attribute-list declarations encountered after a reference to a parameter entity that is not read, since the entity may have contained overriding declarations.

Using XML Processors

The behavior of a validating XML processor is highly predictable; it must read every piece of a document and report all well-formedness and validity violations. Less is required of a non-validating processor; it need not read any part of the document other than the document entity. This has two effects that may be important to users of XML processors:

Certain well-formedness errors, specifically those that require reading external entities, may not be detected by a non-validating processor. Examples include the constraints entitled Entity Declared, Parsed Entity, and No Recursion, as well as some of the cases described as forbidden in .

The information passed from the processor to the application may vary, depending on whether the processor reads parameter and external entities. For example, a non-validating processor may not normalize attribute values, include the replacement text of internal entities, or supply default attribute values, where doing so depends on having read declarations in external or parameter entities.

For maximum reliability in interoperating between different XML processors, applications which use non-validating processors should not rely on any behaviors not required of such processors. Applications which require facilities such as the use of default attributes or internal entities which are declared in external entities should use validating XML processors.

Notation

The formal grammar of XML is given in this specification using a simple Extended Backus-Naur Form (EBNF) notation. Each rule in the grammar defines one symbol, in the form symbol ::= expression

Symbols are written with an initial capital letter if they are defined by a regular expression, or with an initial lower case letter otherwise. Literal strings are quoted.

Within the expression on the right-hand side of a rule, the following expressions are used to match strings of one or more characters:

where N is a hexadecimal integer, the expression matches the character in ISO/IEC 10646 whose canonical (UCS-4) code value, when interpreted as an unsigned binary number, has the value indicated. The number of leading zeros in the #xN form is insignificant; the number of leading zeros in the corresponding code value is governed by the character encoding in use and is not significant for XML.

matches any character with a value in the range(s) indicated (inclusive).

matches any character with a value outside the range indicated.

matches any character with a value not among the characters given.

matches a literal string matching that given inside the double quotes.

matches a literal string matching that given inside the single quotes.

These symbols may be combined to match more complex patterns as follows, where A and B represent simple expressions:

expression is treated as a unit and may be combined as described in this list.

matches A or nothing; optional A.

matches A followed by B.

matches A or B but not both.

matches any string that matches A but does not match B.

matches one or more occurrences of A.

matches zero or more occurrences of A.

Other notations used in the productions are:

comment.

well-formedness constraint; this identifies by name a constraint on well-formed documents associated with a production.

validity constraint; this identifies by name a constraint on valid documents associated with a production.

References Normative References (Internet Assigned Numbers Authority) Official Names for Character Sets, ed. Keld Simonsen et al. See ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets. IETF (Internet Engineering Task Force). RFC 1766: Tags for the Identification of Languages, ed. H. Alvestrand. 1995. (International Organization for Standardization). ISO 639:1988 (E). Code for the representation of names of languages. [Geneva]: International Organization for Standardization, 1988. (International Organization for Standardization). ISO 3166-1:1997 (E). Codes for the representation of names of countries and their subdivisions — Part 1: Country codes [Geneva]: International Organization for Standardization, 1997. ISO (International Organization for Standardization). ISO/IEC 10646-1993 (E). Information technology — Universal Multiple-Octet Coded Character Set (UCS) — Part 1: Architecture and Basic Multilingual Plane. [Geneva]: International Organization for Standardization, 1993 (plus amendments AM 1 through AM 7). The Unicode Consortium. The Unicode Standard, Version 2.0. Reading, Mass.: Addison-Wesley Developers Press, 1996. Other References Aho, Alfred V., Ravi Sethi, and Jeffrey D. Ullman. Compilers: Principles, Techniques, and Tools. Reading: Addison-Wesley, 1986, rpt. corr. 1988. Berners-Lee, T., R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax and Semantics. 1997. (Work in progress; see updates to RFC1738.) Brüggemann-Klein, Anne. Regular Expressions into Finite Automata. Extended abstract in I. Simon, Hrsg., LATIN 1992, S. 97-98. Springer-Verlag, Berlin 1992. Full Version in Theoretical Computer Science 120: 197-213, 1993. Brüggemann-Klein, Anne, and Derick Wood. Deterministic Regular Languages. Universität Freiburg, Institut für Informatik, Bericht 38, Oktober 1991. James Clark. Comparison of SGML and XML. See http://www.w3.org/TR/NOTE-sgml-xml-971215. IETF (Internet Engineering Task Force). RFC 1738: Uniform Resource Locators (URL), ed. T. Berners-Lee, L. Masinter, M. McCahill. 1994. IETF (Internet Engineering Task Force). RFC 1808: Relative Uniform Resource Locators, ed. R. Fielding. 1995. IETF (Internet Engineering Task Force). RFC 2141: URN Syntax, ed. R. Moats. 1997. ISO (International Organization for Standardization). ISO 8879:1986(E). Information processing — Text and Office Systems — Standard Generalized Markup Language (SGML). First edition — 1986-10-15. [Geneva]: International Organization for Standardization, 1986. ISO (International Organization for Standardization). ISO/IEC 10744-1992 (E). Information technology — Hypermedia/Time-based Structuring Language (HyTime). [Geneva]: International Organization for Standardization, 1992. Extended Facilities Annexe. [Geneva]: International Organization for Standardization, 1996. Character Classes

Following the characteristics defined in the Unicode standard, characters are classed as base characters (among others, these contain the alphabetic characters of the Latin alphabet, without diacritics), ideographic characters, and combining characters (among others, this class contains most diacritics); these classes combine to form the class of letters. Digits and extenders are also distinguished. Characters Letter BaseChar | Ideographic BaseChar [#x0041-#x005A] | [#x0061-#x007A] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x00FF] | [#x0100-#x0131] | [#x0134-#x013E] | [#x0141-#x0148] | [#x014A-#x017E] | [#x0180-#x01C3] | [#x01CD-#x01F0] | [#x01F4-#x01F5] | [#x01FA-#x0217] | [#x0250-#x02A8] | [#x02BB-#x02C1] | #x0386 | [#x0388-#x038A] | #x038C | [#x038E-#x03A1] | [#x03A3-#x03CE] | [#x03D0-#x03D6] | #x03DA | #x03DC | #x03DE | #x03E0 | [#x03E2-#x03F3] | [#x0401-#x040C] | [#x040E-#x044F] | [#x0451-#x045C] | [#x045E-#x0481] | [#x0490-#x04C4] | [#x04C7-#x04C8] | [#x04CB-#x04CC] | [#x04D0-#x04EB] | [#x04EE-#x04F5] | [#x04F8-#x04F9] | [#x0531-#x0556] | #x0559 | [#x0561-#x0586] | [#x05D0-#x05EA] | [#x05F0-#x05F2] | [#x0621-#x063A] | [#x0641-#x064A] | [#x0671-#x06B7] | [#x06BA-#x06BE] | [#x06C0-#x06CE] | [#x06D0-#x06D3] | #x06D5 | [#x06E5-#x06E6] | [#x0905-#x0939] | #x093D | [#x0958-#x0961] | [#x0985-#x098C] | [#x098F-#x0990] | [#x0993-#x09A8] | [#x09AA-#x09B0] | #x09B2 | [#x09B6-#x09B9] | [#x09DC-#x09DD] | [#x09DF-#x09E1] | [#x09F0-#x09F1] | [#x0A05-#x0A0A] | [#x0A0F-#x0A10] | [#x0A13-#x0A28] | [#x0A2A-#x0A30] | [#x0A32-#x0A33] | [#x0A35-#x0A36] | [#x0A38-#x0A39] | [#x0A59-#x0A5C] | #x0A5E | [#x0A72-#x0A74] | [#x0A85-#x0A8B] | #x0A8D | [#x0A8F-#x0A91] | [#x0A93-#x0AA8] | [#x0AAA-#x0AB0] | [#x0AB2-#x0AB3] | [#x0AB5-#x0AB9] | #x0ABD | #x0AE0 | [#x0B05-#x0B0C] | [#x0B0F-#x0B10] | [#x0B13-#x0B28] | [#x0B2A-#x0B30] | [#x0B32-#x0B33] | [#x0B36-#x0B39] | #x0B3D | [#x0B5C-#x0B5D] | [#x0B5F-#x0B61] | [#x0B85-#x0B8A] | [#x0B8E-#x0B90] | [#x0B92-#x0B95] | [#x0B99-#x0B9A] | #x0B9C | [#x0B9E-#x0B9F] | [#x0BA3-#x0BA4] | [#x0BA8-#x0BAA] | [#x0BAE-#x0BB5] | [#x0BB7-#x0BB9] | [#x0C05-#x0C0C] | [#x0C0E-#x0C10] | [#x0C12-#x0C28] | [#x0C2A-#x0C33] | [#x0C35-#x0C39] | [#x0C60-#x0C61] | [#x0C85-#x0C8C] | [#x0C8E-#x0C90] | [#x0C92-#x0CA8] | [#x0CAA-#x0CB3] | [#x0CB5-#x0CB9] | #x0CDE | [#x0CE0-#x0CE1] | [#x0D05-#x0D0C] | [#x0D0E-#x0D10] | [#x0D12-#x0D28] | [#x0D2A-#x0D39] | [#x0D60-#x0D61] | [#x0E01-#x0E2E] | #x0E30 | [#x0E32-#x0E33] | [#x0E40-#x0E45] | [#x0E81-#x0E82] | #x0E84 | [#x0E87-#x0E88] | #x0E8A | #x0E8D | [#x0E94-#x0E97] | [#x0E99-#x0E9F] | [#x0EA1-#x0EA3] | #x0EA5 | #x0EA7 | [#x0EAA-#x0EAB] | [#x0EAD-#x0EAE] | #x0EB0 | [#x0EB2-#x0EB3] | #x0EBD | [#x0EC0-#x0EC4] | [#x0F40-#x0F47] | [#x0F49-#x0F69] | [#x10A0-#x10C5] | [#x10D0-#x10F6] | #x1100 | [#x1102-#x1103] | [#x1105-#x1107] | #x1109 | [#x110B-#x110C] | [#x110E-#x1112] | #x113C | #x113E | #x1140 | #x114C | #x114E | #x1150 | [#x1154-#x1155] | #x1159 | [#x115F-#x1161] | #x1163 | #x1165 | #x1167 | #x1169 | [#x116D-#x116E] | [#x1172-#x1173] | #x1175 | #x119E | #x11A8 | #x11AB | [#x11AE-#x11AF] | [#x11B7-#x11B8] | #x11BA | [#x11BC-#x11C2] | #x11EB | #x11F0 | #x11F9 | [#x1E00-#x1E9B] | [#x1EA0-#x1EF9] | [#x1F00-#x1F15] | [#x1F18-#x1F1D] | [#x1F20-#x1F45] | [#x1F48-#x1F4D] | [#x1F50-#x1F57] | #x1F59 | #x1F5B | #x1F5D | [#x1F5F-#x1F7D] | [#x1F80-#x1FB4] | [#x1FB6-#x1FBC] | #x1FBE | [#x1FC2-#x1FC4] | [#x1FC6-#x1FCC] | [#x1FD0-#x1FD3] | [#x1FD6-#x1FDB] | [#x1FE0-#x1FEC] | [#x1FF2-#x1FF4] | [#x1FF6-#x1FFC] | #x2126 | [#x212A-#x212B] | #x212E | [#x2180-#x2182] | [#x3041-#x3094] | [#x30A1-#x30FA] | [#x3105-#x312C] | [#xAC00-#xD7A3] Ideographic [#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029] CombiningChar [#x0300-#x0345] | [#x0360-#x0361] | [#x0483-#x0486] | [#x0591-#x05A1] | [#x05A3-#x05B9] | [#x05BB-#x05BD] | #x05BF | [#x05C1-#x05C2] | #x05C4 | [#x064B-#x0652] | #x0670 | [#x06D6-#x06DC] | [#x06DD-#x06DF] | [#x06E0-#x06E4] | [#x06E7-#x06E8] | [#x06EA-#x06ED] | [#x0901-#x0903] | #x093C | [#x093E-#x094C] | #x094D | [#x0951-#x0954] | [#x0962-#x0963] | [#x0981-#x0983] | #x09BC | #x09BE | #x09BF | [#x09C0-#x09C4] | [#x09C7-#x09C8] | [#x09CB-#x09CD] | #x09D7 | [#x09E2-#x09E3] | #x0A02 | #x0A3C | #x0A3E | #x0A3F | [#x0A40-#x0A42] | [#x0A47-#x0A48] | [#x0A4B-#x0A4D] | [#x0A70-#x0A71] | [#x0A81-#x0A83] | #x0ABC | [#x0ABE-#x0AC5] | [#x0AC7-#x0AC9] | [#x0ACB-#x0ACD] | [#x0B01-#x0B03] | #x0B3C | [#x0B3E-#x0B43] | [#x0B47-#x0B48] | [#x0B4B-#x0B4D] | [#x0B56-#x0B57] | [#x0B82-#x0B83] | [#x0BBE-#x0BC2] | [#x0BC6-#x0BC8] | [#x0BCA-#x0BCD] | #x0BD7 | [#x0C01-#x0C03] | [#x0C3E-#x0C44] | [#x0C46-#x0C48] | [#x0C4A-#x0C4D] | [#x0C55-#x0C56] | [#x0C82-#x0C83] | [#x0CBE-#x0CC4] | [#x0CC6-#x0CC8] | [#x0CCA-#x0CCD] | [#x0CD5-#x0CD6] | [#x0D02-#x0D03] | [#x0D3E-#x0D43] | [#x0D46-#x0D48] | [#x0D4A-#x0D4D] | #x0D57 | #x0E31 | [#x0E34-#x0E3A] | [#x0E47-#x0E4E] | #x0EB1 | [#x0EB4-#x0EB9] | [#x0EBB-#x0EBC] | [#x0EC8-#x0ECD] | [#x0F18-#x0F19] | #x0F35 | #x0F37 | #x0F39 | #x0F3E | #x0F3F | [#x0F71-#x0F84] | [#x0F86-#x0F8B] | [#x0F90-#x0F95] | #x0F97 | [#x0F99-#x0FAD] | [#x0FB1-#x0FB7] | #x0FB9 | [#x20D0-#x20DC] | #x20E1 | [#x302A-#x302F] | #x3099 | #x309A Digit [#x0030-#x0039] | [#x0660-#x0669] | [#x06F0-#x06F9] | [#x0966-#x096F] | [#x09E6-#x09EF] | [#x0A66-#x0A6F] | [#x0AE6-#x0AEF] | [#x0B66-#x0B6F] | [#x0BE7-#x0BEF] | [#x0C66-#x0C6F] | [#x0CE6-#x0CEF] | [#x0D66-#x0D6F] | [#x0E50-#x0E59] | [#x0ED0-#x0ED9] | [#x0F20-#x0F29] Extender #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | #x0E46 | #x0EC6 | #x3005 | [#x3031-#x3035] | [#x309D-#x309E] | [#x30FC-#x30FE]

The character classes defined here can be derived from the Unicode character database as follows:

Name start characters must have one of the categories Ll, Lu, Lo, Lt, Nl.

Name characters other than Name-start characters must have one of the categories Mc, Me, Mn, Lm, or Nd.

Characters in the compatibility area (i.e. with character code greater than #xF900 and less than #xFFFE) are not allowed in XML names.

Characters which have a font or compatibility decomposition (i.e. those with a "compatibility formatting tag" in field 5 of the database -- marked by field 5 beginning with a "<") are not allowed.

The following characters are treated as name-start characters rather than name characters, because the property file classifies them as Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.

Characters #x20DD-#x20E0 are excluded (in accordance with Unicode, section 5.14).

Character #x00B7 is classified as an extender, because the property list so identifies it.

Character #x0387 is added as a name character, because #x00B7 is its canonical equivalent.

Characters ':' and '_' are allowed as name-start characters.

Characters '-' and '.' are allowed as name characters.

XML and SGML

XML is designed to be a subset of SGML, in that every valid XML document should also be a conformant SGML document. For a detailed comparison of the additional restrictions that XML places on documents beyond those of SGML, see .

Expansion of Entity and Character References

This appendix contains some examples illustrating the sequence of entity- and character-reference recognition and expansion, as specified in .

If the DTD contains the declaration An ampersand (&#38;) may be escaped numerically (&#38;#38;) or with a general entity (&amp;).

" > ]]> then the XML processor will recognize the character references when it parses the entity declaration, and resolve them before storing the following string as the value of the entity "example": An ampersand (&) may be escaped numerically (&#38;) or with a general entity (&amp;).

]]>
A reference in the document to "&example;" will cause the text to be reparsed, at which time the start- and end-tags of the "p" element will be recognized and the three references will be recognized and expanded, resulting in a "p" element with the following content (all data, no delimiters or markup):

A more complex example will illustrate the rules and their effects fully. In the following example, the line numbers are solely for reference. 2 4 5 ' > 6 %xx; 7 ]> 8 This sample shows a &tricky; method. ]]> This produces the following:

in line 4, the reference to character 37 is expanded immediately, and the parameter entity "xx" is stored in the symbol table with the value "%zz;". Since the replacement text is not rescanned, the reference to parameter entity "zz" is not recognized. (And it would be an error if it were, since "zz" is not yet declared.)

in line 5, the character reference "&#60;" is expanded immediately and the parameter entity "zz" is stored with the replacement text "<!ENTITY tricky "error-prone" >", which is a well-formed entity declaration.

in line 6, the reference to "xx" is recognized, and the replacement text of "xx" (namely "%zz;") is parsed. The reference to "zz" is recognized in its turn, and its replacement text ("<!ENTITY tricky "error-prone" >") is parsed. The general entity "tricky" has now been declared, with the replacement text "error-prone".

in line 8, the reference to the general entity "tricky" is recognized, and it is expanded, so the full content of the "test" element is the self-describing (and ungrammatical) string This sample shows a error-prone method.

Deterministic Content Models

For compatibility, it is required that content models in element type declarations be deterministic.

SGML requires deterministic content models (it calls them "unambiguous"); XML processors built using SGML systems may flag non-deterministic content models as errors.

For example, the content model ((b, c) | (b, d)) is non-deterministic, because given an initial b the parser cannot know which b in the model is being matched without looking ahead to see which element follows the b. In this case, the two references to b can be collapsed into a single reference, making the model read (b, (c | d)). An initial b now clearly matches only a single name in the content model. The parser doesn't need to look ahead to see what follows; either c or d would be accepted.

More formally: a finite state automaton may be constructed from the content model using the standard algorithms, e.g. algorithm 3.5 in section 3.9 of Aho, Sethi, and Ullman . In many such algorithms, a follow set is constructed for each position in the regular expression (i.e., each leaf node in the syntax tree for the regular expression); if any position has a follow set in which more than one following position is labeled with the same element type name, then the content model is in error and may be reported as an error.

Algorithms exist which allow many but not all non-deterministic content models to be reduced automatically to equivalent deterministic models; see Brüggemann-Klein 1991 .

Autodetection of Character Encodings

The XML encoding declaration functions as an internal label on each entity, indicating which character encoding is in use. Before an XML processor can read the internal label, however, it apparently has to know what character encoding is in use—which is what the internal label is trying to indicate. In the general case, this is a hopeless situation. It is not entirely hopeless in XML, however, because XML limits the general case in two ways: each implementation is assumed to support only a finite set of character encodings, and the XML encoding declaration is restricted in position and content in order to make it feasible to autodetect the character encoding in use in each entity in normal cases. Also, in many cases other sources of information are available in addition to the XML data stream itself. Two cases may be distinguished, depending on whether the XML entity is presented to the processor without, or with, any accompanying (external) information. We consider the first case first.

Because each XML entity not in UTF-8 or UTF-16 format must begin with an XML encoding declaration, in which the first characters must be '<?xml', any conforming processor can detect, after two to four octets of input, which of the following cases apply. In reading this list, it may help to know that in UCS-4, '<' is "#x0000003C" and '?' is "#x0000003F", and the Byte Order Mark required of UTF-16 data streams is "#xFEFF".

00 00 00 3C: UCS-4, big-endian machine (1234 order)

3C 00 00 00: UCS-4, little-endian machine (4321 order)

00 00 3C 00: UCS-4, unusual octet order (2143)

00 3C 00 00: UCS-4, unusual octet order (3412)

FE FF: UTF-16, big-endian

FF FE: UTF-16, little-endian

00 3C 00 3F: UTF-16, big-endian, no Byte Order Mark (and thus, strictly speaking, in error)

3C 00 3F 00: UTF-16, little-endian, no Byte Order Mark (and thus, strictly speaking, in error)

3C 3F 78 6D: UTF-8, ISO 646, ASCII, some part of ISO 8859, Shift-JIS, EUC, or any other 7-bit, 8-bit, or mixed-width encoding which ensures that the characters of ASCII have their normal positions, width, and values; the actual encoding declaration must be read to detect which of these applies, but since all of these encodings use the same bit patterns for the ASCII characters, the encoding declaration itself may be read reliably

4C 6F A7 94: EBCDIC (in some flavor; the full encoding declaration must be read to tell which code page is in use)

other: UTF-8 without an encoding declaration, or else the data stream is corrupt, fragmentary, or enclosed in a wrapper of some kind

This level of autodetection is enough to read the XML encoding declaration and parse the character-encoding identifier, which is still necessary to distinguish the individual members of each family of encodings (e.g. to tell UTF-8 from 8859, and the parts of 8859 from each other, or to distinguish the specific EBCDIC code page in use, and so on).

Because the contents of the encoding declaration are restricted to ASCII characters, a processor can reliably read the entire encoding declaration as soon as it has detected which family of encodings is in use. Since in practice, all widely used character encodings fall into one of the categories above, the XML encoding declaration allows reasonably reliable in-band labeling of character encodings, even when external sources of information at the operating-system or transport-protocol level are unreliable.

Once the processor has detected the character encoding in use, it can act appropriately, whether by invoking a separate input routine for each case, or by calling the proper conversion function on each character of input.

Like any self-labeling system, the XML encoding declaration will not work if any software changes the entity's character set or encoding without updating the encoding declaration. Implementors of character-encoding routines should be careful to ensure the accuracy of the internal and external information used to label the entity.

The second possible case occurs when the XML entity is accompanied by encoding information, as in some file systems and some network protocols. When multiple sources of information are available, their relative priority and the preferred method of handling conflict should be specified as part of the higher-level protocol used to deliver XML. Rules for the relative priority of the internal label and the MIME-type label in an external header, for example, should be part of the RFC document defining the text/xml and application/xml MIME types. In the interests of interoperability, however, the following rules are recommended.

If an XML entity is in a file, the Byte-Order Mark and encoding-declaration PI are used (if present) to determine the character encoding. All other heuristics and sources of information are solely for error recovery.

If an XML entity is delivered with a MIME type of text/xml, then the charset parameter on the MIME type determines the character encoding method; all other heuristics and sources of information are solely for error recovery.

If an XML entity is delivered with a MIME type of application/xml, then the Byte-Order Mark and encoding-declaration PI are used (if present) to determine the character encoding. All other heuristics and sources of information are solely for error recovery.

These rules apply only in the absence of protocol-level documentation; in particular, when the MIME types text/xml and application/xml are defined, the recommendations of the relevant RFC will supersede these rules.

W3C XML Working Group

This specification was prepared and approved for publication by the W3C XML Working Group (WG). WG approval of this specification does not necessarily imply that all WG members voted for its approval. The current and former members of the XML WG are:

Jon Bosak, SunChair James ClarkTechnical Lead Tim Bray, Textuality and NetscapeXML Co-editor Jean Paoli, MicrosoftXML Co-editor C. M. Sperberg-McQueen, U. of Ill.XML Co-editor Dan Connolly, W3CW3C Liaison Paula Angerstein, Texcel Steve DeRose, INSO Dave Hollander, HP Eliot Kimber, ISOGEN Eve Maler, ArborText Tom Magliery, NCSA Murray Maloney, Muzmo and Grif Makoto Murata, Fuji Xerox Information Systems Joel Nava, Adobe Conleth O'Connell, Vignette Peter Sharpe, SoftQuad John Tigue, DataChannel
XML-XQL-0.68/README0100644000076500007650000000223707314127325013672 0ustar tjmathertjmather Perl module: XML-XQL Copyright (c) 1999,2000 Enno Derksen All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The XML::XQL module is alpha code. For bug reports or suggestions send email to tjmather@tjmather.com ============= XML::XQL ========================================================= This is a Perl extension that allows you to perform XQL queries on XML object trees. Currently only the XML::DOM module is supported, but other implementations, like XML::Grove, may soon follow. See the XML::XQL and XML::XQL::Tutorial man pages that come with this distribution. See the XQL specification for more details, it's at: http://www.w3.org/TandS/QL/QL98/pp/xql.html Look at the test cases in the 't' directory for examples. Check out xql.pl, which is a nice command line utility for performing XQL queries on XML documents and formatting the results in several ways. XML::XQL needs the following modules to be installed: XML::DOM, XML::Parser, Parse::Yapp (I use 0.16) and Date::Manip (I use 5.33). All can be found at CPAN. See the To-do list at the top of XQL.pm for all open issues. XML-XQL-0.68/Makefile.PL0100644000076500007650000000133607314125005014754 0ustar tjmathertjmatheruse ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'XML::XQL', 'VERSION_FROM' => 'lib/XML/XQL.pm', # finds $VERSION 'PREREQ_PM' => { 'XML::Parser' => '2.30', # Maybe requiring Date::Manip 5.33 is too strict, # it's what I was using. I know 5.20 doesn't work. # I also know that 5.36 works. 'Date::Manip' => '5.33', 'Parse::Yapp' => '0', # LWP::UserAgent is used when parsing XML from URLs # It's part of libwww-perl, and you don't strictly need it # (some test cases may fail) 'LWP::UserAgent' => '0', 'XML::DOM' => '1.29'}, EXE_FILES => [ 'bin/xql.pl' ], );