source: exist/branches/proglue_production_rev4605_xquery4884/python/elementtree-1.3a6-20070310-badc/elementtree/ElementPath.py @ 4886

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/exist/branches/proglue_production_rev4605_xquery4884/python/elementtree-1.3a6-20070310-badc/elementtree/ElementPath.py@4886
Revision 4886, 8.7 KB checked in by sdonegan, 10 years ago (diff)

Creating operational branch for ndgUtils as used on proglue

Line 
1#
2# ElementTree
3# $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $
4#
5# limited xpath support for element trees
6#
7# history:
8# 2003-05-23 fl   created
9# 2003-05-28 fl   added support for // etc
10# 2003-08-27 fl   fixed parsing of periods in element names
11# 2007-09-10 fl   new selection engine
12# 2007-09-12 fl   fixed parent selector
13# 2007-09-13 fl   added iterfind; changed findall to return a list
14# 2007-11-30 fl   added namespaces support
15#
16# Copyright (c) 2003-2008 by Fredrik Lundh.  All rights reserved.
17#
18# fredrik@pythonware.com
19# http://www.pythonware.com
20#
21# --------------------------------------------------------------------
22# The ElementTree toolkit is
23#
24# Copyright (c) 1999-2008 by Fredrik Lundh
25#
26# By obtaining, using, and/or copying this software and/or its
27# associated documentation, you agree that you have read, understood,
28# and will comply with the following terms and conditions:
29#
30# Permission to use, copy, modify, and distribute this software and
31# its associated documentation for any purpose and without fee is
32# hereby granted, provided that the above copyright notice appears in
33# all copies, and that both that copyright notice and this permission
34# notice appear in supporting documentation, and that the name of
35# Secret Labs AB or the author not be used in advertising or publicity
36# pertaining to distribution of the software without specific, written
37# prior permission.
38#
39# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
40# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
41# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
42# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
43# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
44# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
45# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
46# OF THIS SOFTWARE.
47# --------------------------------------------------------------------
48
49##
50# Implementation module for XPath support.  There's usually no reason
51# to import this module directly; the <b>ElementTree</b> does this for
52# you, if needed.
53##
54
55import re, sys
56
57xpath_tokenizer_re = re.compile(
58    "("
59    "'[^']*'|\"[^\"]*\"|"
60    "::|"
61    "//?|"
62    "\.\.|"
63    "\(\)|"
64    "[/.*:\[\]\(\)@=])|"
65    "((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|"
66    "\s+"
67    )
68
69def xpath_tokenizer(pattern, namespaces=None):
70    for token in xpath_tokenizer_re.findall(pattern):
71        tag = token[1]
72        if tag and tag[0] != "{" and ":" in tag:
73            try:
74                prefix, uri = tag.split(":", 1)
75                if not namespaces:
76                    raise KeyError
77                yield token[0], "{%s}%s" % (namespaces[prefix], uri)
78            except KeyError:
79                raise SyntaxError("prefix %r not found in prefix map" % prefix)
80        else:
81            yield token
82
83def get_parent_map(context):
84    parent_map = context.parent_map
85    if parent_map is None:
86        context.parent_map = parent_map = {}
87        for p in context.root.iter():
88            for e in p:
89                parent_map[e] = p
90    return parent_map
91
92def prepare_child(next, token):
93    tag = token[1]
94    def select(context, result):
95        for elem in result:
96            for e in elem:
97                if e.tag == tag:
98                    yield e
99    return select
100
101def prepare_star(next, token):
102    def select(context, result):
103        for elem in result:
104            for e in elem:
105                yield e
106    return select
107
108def prepare_self(next, token):
109    def select(context, result):
110        for elem in result:
111            yield elem
112    return select
113
114def prepare_descendant(next, token):
115    token = next()
116    if token[0] == "*":
117        tag = "*"
118    elif not token[0]:
119        tag = token[1]
120    else:
121        raise SyntaxError("invalid descendant")
122    def select(context, result):
123        for elem in result:
124            for e in elem.iter(tag):
125                if e is not elem:
126                    yield e
127    return select
128
129def prepare_parent(next, token):
130    def select(context, result):
131        # FIXME: raise error if .. is applied at toplevel?
132        parent_map = get_parent_map(context)
133        result_map = {}
134        for elem in result:
135            if elem in parent_map:
136                parent = parent_map[elem]
137                if parent not in result_map:
138                    result_map[parent] = None
139                    yield parent
140    return select
141
142def prepare_predicate(next, token):
143    # FIXME: replace with real parser!!! refs:
144    # http://effbot.org/zone/simple-iterator-parser.htm
145    # http://javascript.crockford.com/tdop/tdop.html
146    signature = []
147    predicate = []
148    while 1:
149        token = next()
150        if token[0] == "]":
151            break
152        if token[0] and token[0][:1] in "'\"":
153            token = "'", token[0][1:-1]
154        signature.append(token[0] or "-")
155        predicate.append(token[1])
156    signature = "".join(signature)
157    # use signature to determine predicate type
158    if signature == "@-":
159        # [@attribute] predicate
160        key = predicate[1]
161        def select(context, result):
162            for elem in result:
163                if elem.get(key) is not None:
164                    yield elem
165        return select
166    if signature == "@-='":
167        # [@attribute='value']
168        key = predicate[1]
169        value = predicate[-1]
170        def select(context, result):
171            for elem in result:
172                if elem.get(key) == value:
173                    yield elem
174        return select
175    if signature == "-" and not re.match("\d+$", predicate[0]):
176        # [tag]
177        tag = predicate[0]
178        def select(context, result):
179            for elem in result:
180                if elem.find(tag) is not None:
181                    yield elem
182        return select
183    if signature == "-" or signature == "-()" or signature == "-()-":
184        # [index] or [last()] or [last()-index]
185        if signature == "-":
186            index = int(predicate[0])-1
187        else:
188            if predicate[0] != "last":
189                raise SyntaxError("unsupported function")
190            if signature == "-()-":
191                try:
192                    index = int(predicate[2]) - 1
193                except ValueError:
194                    raise SyntaxError("unsupported expression")
195            else:
196                index = -1
197        def select(context, result):
198            parent_map = get_parent_map(context)
199            for elem in result:
200                try:
201                    parent = parent_map[elem]
202                    # FIXME: what if the selector is "*" ?
203                    elems = list(parent.findall(elem.tag))
204                    if elems[index] is elem:
205                        yield elem
206                except (IndexError, KeyError):
207                    pass
208        return select
209    raise SyntaxError("invalid predicate")
210
211ops = {
212    "": prepare_child,
213    "*": prepare_star,
214    ".": prepare_self,
215    "..": prepare_parent,
216    "//": prepare_descendant,
217    "[": prepare_predicate,
218    }
219
220_cache = {}
221
222class _SelectorContext:
223    parent_map = None
224    def __init__(self, root):
225        self.root = root
226
227# --------------------------------------------------------------------
228
229##
230# Generate all matching objects.
231
232def iterfind(elem, path, namespaces=None):
233    # compile selector pattern
234    if path[-1:] == "/":
235        path = path + "*" # implicit all (FIXME: keep this?)
236    try:
237        selector = _cache[path]
238    except KeyError:
239        if len(_cache) > 100:
240            _cache.clear()
241        if path[:1] == "/":
242            raise SyntaxError("cannot use absolute path on element")
243        stream = iter(xpath_tokenizer(path, namespaces))
244        next = stream.next; token = next()
245        selector = []
246        while 1:
247            try:
248                selector.append(ops[token[0]](next, token))
249            except StopIteration:
250                raise SyntaxError("invalid path")
251            try:
252                token = next()
253                if token[0] == "/":
254                    token = next()
255            except StopIteration:
256                break
257        _cache[path] = selector
258    # execute selector pattern
259    result = [elem]
260    context = _SelectorContext(elem)
261    for select in selector:
262        result = select(context, result)
263    return result
264
265##
266# Find first matching object.
267
268def find(elem, path, namespaces=None):
269    try:
270        return iterfind(elem, path, namespaces).next()
271    except StopIteration:
272        return None
273
274##
275# Find all matching objects.
276
277def findall(elem, path, namespaces=None):
278    return list(iterfind(elem, path, namespaces))
279
280##
281# Find text for first matching object.
282
283def findtext(elem, path, default=None, namespaces=None):
284    try:
285        elem = iterfind(elem, path, namespaces).next()
286        return elem.text
287    except StopIteration:
288        return default
Note: See TracBrowser for help on using the repository browser.