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

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/exist/branches/proglue_production_rev4605_xquery4884/python/elementtree-1.3a5-20070114-badc/elementtree/ElementPath.py@4886
Revision 4886, 8.9 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 3341 2007-12-19 18:24:41Z 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-2007 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-2007 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    # silly parser
144    signature = []
145    predicate = []
146    while 1:
147        token = next()
148        if token[0] == "]":
149            break
150        if token[0] and token[0][:1] in "'\"":
151            token = "'", token[0][1:-1]
152        signature.append(token[0] or "-")
153        predicate.append(token[1])
154    signature = "".join(signature)
155    # use signature to determine predicate type
156    if signature == "@-":
157        # [@attribute] predicate
158        key = predicate[1]
159        def select(context, result):
160            for elem in result:
161                if elem.get(key) is not None:
162                    yield elem
163        return select
164    if signature == "@-='":
165        # [@attribute='value']
166        key = predicate[1]
167        value = predicate[-1]
168        def select(context, result):
169            for elem in result:
170                if elem.get(key) == value:
171                    yield elem
172        return select
173    if signature == "-" and not re.match("\d+$", predicate[0]):
174        # [tag]
175        tag = predicate[0]
176        def select(context, result):
177            for elem in result:
178                if elem.find(tag) is not None:
179                    yield elem
180        return select
181    if signature == "-" or signature == "-()" or signature == "-()-":
182        # [index] or [last()] or [last()-index]
183        if signature == "-":
184            index = int(predicate[0])-1
185        else:
186            if predicate[0] != "last":
187                raise SyntaxError("unsupported function")
188            if signature == "-()-":
189                try:
190                    index = int(predicate[2]) - 1
191                except ValueError:
192                    raise SyntaxError("unsupported expression")
193            else:
194                index = -1
195        def select(context, result):
196            parent_map = get_parent_map(context)
197            for elem in result:
198                try:
199                    parent = parent_map[elem]
200                    # FIXME: what if the selector is "*" ?
201                    elems = list(parent.findall(elem.tag))
202                    if elems[index] is elem:
203                        yield elem
204                except (IndexError, KeyError):
205                    pass
206        return select
207    raise SyntaxError("invalid predicate")
208
209ops = {
210    "": prepare_child,
211    "*": prepare_star,
212    ".": prepare_self,
213    "..": prepare_parent,
214    "//": prepare_descendant,
215    "[": prepare_predicate,
216    }
217
218_cache = {}
219
220class _SelectorContext:
221    parent_map = None
222    def __init__(self, root):
223        self.root = root
224
225# --------------------------------------------------------------------
226
227##
228# Generate all matching objects.
229
230def iterfind(elem, path, namespaces=None):
231    # compile selector pattern
232    if path[-1:] == "/":
233        path = path + "*" # implicit all (FIXME: keep this?)
234    try:
235        selector = _cache[path]
236    except KeyError:
237        if len(_cache) > 100:
238            _cache.clear()
239        if path[:1] == "/":
240            raise SyntaxError("cannot use absolute path on element")
241        stream = iter(xpath_tokenizer(path, namespaces))
242        next = stream.next; token = next()
243        selector = []
244        while 1:
245            try:
246                selector.append(ops[token[0]](next, token))
247            except StopIteration:
248                raise SyntaxError("invalid path")
249            try:
250                token = next()
251                if token[0] == "/":
252                    token = next()
253            except StopIteration:
254                break
255        _cache[path] = selector
256    # execute selector pattern
257    result = [elem]
258    context = _SelectorContext(elem)
259    for select in selector:
260        result = select(context, result)
261    return result
262
263##
264# Find first matching object.
265
266def find(elem, path, namespaces=None):
267    try:
268        return iterfind(elem, path, namespaces).next()
269    except StopIteration:
270        return None
271
272##
273# Find all matching objects.
274
275def findall(elem, path, namespaces=None):
276    return list(iterfind(elem, path, namespaces))
277
278##
279# Find text for first matching object.
280
281def findtext(elem, path, default=None, namespaces=None):
282    try:
283        elem = iterfind(elem, path, namespaces).next()
284        return elem.text
285    except StopIteration:
286        return default
Note: See TracBrowser for help on using the repository browser.