[XML-SIG] Tiny XPath implementation
Paul Prescod
paul@prescod.net
Mon, 10 Jul 2000 01:30:39 -0500
Okay, I took my own challenge and implemented a small subset of xpath. I
call it tinyxpath (minixpath was taken :) ).
It does the 10% of XPath that people use 90% of the time and leaves out
many features that are easier done in Python code rather than directly
in XPath. It is less than 250 lines of code.
Here is an example of tinyxpath code, using Hamlet. Pretty much all of
the useful features are shown in these examples. Conspicuously absent
are qualifiers and attributes but I propose that Python fetuares should
be used for those (as shown)
tinyxpath.select( dom, "/PLAY/ACT/TITLE/text()" )
# get a list of text within all ACT TITLEs in Hamlet
tinyxpath.select( dom, ".//TITLE/text()" )
# text within all title nodes in Hamlet (no matter how deep)
tinyxpath.select( dom, ".//TITLE/text()" )[1]
# get first text node in title in Hamlet (no matter how deep)
tinyxpath.select( dom, ".//TITLE" )[1].getAttribute( "french_trans" )
# french_trans attr of first title in Hamlet (no matter how deep)
tinyxpath.select( dom, ".//TITLE/.." )
# Find titles and then get a list of their parent nodes
tinyxpath.select( dom, "PLAY/*/TITLE" )
# all titles once removed from play
tinyxpath.select( dom, "PLAY/*/*" )
# all elements once removed from play
tinyxpath.select( dom, "PLAY/*/node()" )
# all nodes once removed from play
tinyxpath.select( dom, "/" )
# the root node
tinyxpath.select( dom, "/PLAY" )
# the root element
node = tinyxpath.select( dom, "PLAY/ACT/TITLE" )
# set up variable for the rest
assert tinyxpath.match( node, "TITLE" )==1
assert tinyxpath.match( node, "ACT/TITLE" )==1
assert tinyxpath.match( node, "PLAY//TITLE" )==1
assert tinyxpath.match( node, "/PLAY/ACT/TITLE" )==1
assert tinyxpath.match( node, "PLAY/*/TITLE" )==1
assert tinyxpath.match( node, "PLAY/FOO/TITLE" )==0
assert tinyxpath.match( node, "//TITLE" )==1
--
Paul Prescod - Not encumbered by corporate consensus
"Computer Associates is expected to come in with better than expected
earnings." Bob O'Brien, quoted in
- http://www.fool.com/news/2000/foth000316.htm