Project

General

Profile

1 55 aaronmk
# XPath parsing
2 21 aaronmk
3 55 aaronmk
import copy
4 21 aaronmk
5
from Parser import Parser
6 892 aaronmk
import util
7 77 aaronmk
import xml_dom
8 21 aaronmk
9 1001 aaronmk
##### Path elements
10
11 21 aaronmk
class XpathElem:
12 94 aaronmk
    def __init__(self, name, value=None, is_attr=False):
13 156 aaronmk
        if name == '': name = '.'
14 21 aaronmk
        self.name = name
15
        self.value = value
16
        self.is_attr = is_attr
17 97 aaronmk
        self.is_positive = True
18 94 aaronmk
        self.is_ptr = False
19
        self.keys = []
20
        self.attrs = []
21 78 aaronmk
        self.other_branches = [] # temp implementation for split paths
22 21 aaronmk
23
    def __repr__(self):
24
        str_ = ''
25 141 aaronmk
        if not self.is_positive: str_ += '!'
26 21 aaronmk
        if self.is_attr: str_ += '@'
27 25 aaronmk
        str_ += self.name
28 94 aaronmk
        if self.keys != []: str_ += repr(self.keys)
29
        if self.attrs != []: str_ += ':'+repr(self.attrs)
30
        if self.is_ptr: str_ += '->'
31
        if self.other_branches != []: str_ += '{'+repr(self.other_branches)+'}'
32 25 aaronmk
        if self.value != None: str_ += '='+repr(self.value)
33 21 aaronmk
        return str_
34
35
    def __eq__(self, other): return self.__dict__ == other.__dict__
36
37 1001 aaronmk
##### Paths
38
39 99 aaronmk
def is_positive(path): return path[0].is_positive
40
41 24 aaronmk
def value(path): return path[-1].value
42
43 22 aaronmk
def set_value(path, value): path[-1].value = value
44
45 32 aaronmk
def backward_id(elem):
46 171 aaronmk
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
47 32 aaronmk
    else: return None
48
49 1001 aaronmk
instance_level = 1 # root's grandchildren
50
51
def obj(path):
52
    obj_path = copy.deepcopy(path[:instance_level+1])
53
    obj_path[-1].is_ptr = False # prevent pointer w/o target
54
    return obj_path
55
56
def set_id(path, id_, has_types=True):
57
    if has_types: id_level = instance_level
58
    else: id_level = 0 # root's children
59
    if path[0].name == '.': id_level += 1 # explicit root element
60
    path[id_level].keys.append([XpathElem('id', id_, True)])
61
62
def is_id(path): return path[0].is_attr and path[0].name == 'id'
63
64
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
65
66
##### Parsing
67
68 170 aaronmk
def expand_abbr(name, repl):
69
    before, abbr, after = name.partition('*')
70
    if abbr != '': name = before+repl+after
71
    return name
72
73 154 aaronmk
_cache = {}
74
75 76 aaronmk
def parse(str_):
76 154 aaronmk
    try: return _cache[str_]
77
    except KeyError: pass
78
79 76 aaronmk
    parser = Parser(str_)
80 21 aaronmk
81 76 aaronmk
    def _path():
82 97 aaronmk
        is_positive = not parser.str_('!')
83
84 21 aaronmk
        tree = []
85
        while True:
86 38 aaronmk
            # Split path
87 76 aaronmk
            if parser.str_('{'):
88 94 aaronmk
                tree[-1].other_branches = _paths()
89 76 aaronmk
                parser.str_('}', required=True)
90 94 aaronmk
                tree += tree[-1].other_branches.pop(0) # use first path for now
91 38 aaronmk
                break # nothing allowed after split path
92 36 aaronmk
93 754 aaronmk
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
94 38 aaronmk
95 94 aaronmk
            # Keys used to match nodes
96 76 aaronmk
            if parser.str_('['):
97 94 aaronmk
                elem.keys = _paths()
98 76 aaronmk
                parser.str_(']', required=True)
99 36 aaronmk
100 94 aaronmk
            # Attrs created when no matching node exists
101
            if parser.str_(':'):
102
                parser.str_('[', required=True)
103
                elem.attrs = _paths()
104
                parser.str_(']', required=True)
105
106 76 aaronmk
            elem.is_ptr = parser.str_('->')
107 21 aaronmk
            tree.append(elem)
108 36 aaronmk
109
            # Lookahead assertion
110 76 aaronmk
            if parser.str_('('):
111
                parser.str_('/', required=True) # next / is inside ()
112
                path = _path()
113
                parser.str_(')', required=True)
114 94 aaronmk
                elem.keys.append(path)
115 36 aaronmk
                tree += path
116
117 76 aaronmk
            if not parser.str_('/'): break
118 32 aaronmk
119 97 aaronmk
        tree[0].is_positive = is_positive
120
121
        # Value
122 997 aaronmk
        if parser.str_('='):
123
            if parser.str_('$'): value = _path()
124
            else: value = _value()
125
            set_value(tree, value)
126 85 aaronmk
127 32 aaronmk
        # Expand * abbrs
128 70 aaronmk
        for i in reversed(xrange(len(tree))):
129
            elem = tree[i]
130 171 aaronmk
            if elem.is_ptr: offset = 2
131 32 aaronmk
            else: offset = 1
132 170 aaronmk
            try: repl = tree[i+offset].name
133 171 aaronmk
            except IndexError: pass # no replacement elem
134
            else: elem.name = expand_abbr(elem.name, repl)
135 32 aaronmk
136 21 aaronmk
        return tree
137 76 aaronmk
138 754 aaronmk
    def _value():
139
        if parser.str_('"'):
140
            value = parser.re(r'[^"]*')
141
            parser.str_('"', required=True)
142
        else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
143
        return value
144
145 94 aaronmk
    def _paths():
146
        paths = []
147
        while True:
148
            paths.append(_path())
149
            if not parser.str_(','): break
150
        return paths
151
152 76 aaronmk
    path = _path()
153
    parser.end()
154 154 aaronmk
    _cache[str_] = path
155 76 aaronmk
    return path
156 21 aaronmk
157 1001 aaronmk
##### Querying/creating XML trees
158 22 aaronmk
159 998 aaronmk
def get(root, xpath, create=False, last_only=None, limit=1):
160 141 aaronmk
    '''Warning: The last_only optimization may put data that should be together
161
    into separate nodes'''
162 77 aaronmk
    if last_only == None: last_only = create
163 887 aaronmk
    if limit == None or limit > 1: last_only = False
164 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
165 99 aaronmk
166 998 aaronmk
    if xpath == []: return [root]
167 886 aaronmk
    if create and not is_positive(xpath): return []
168 998 aaronmk
    doc = root.ownerDocument
169 165 aaronmk
    elem = xpath[0]
170
171
    # Find possible matches
172
    children = []
173
    if elem.is_attr:
174 998 aaronmk
        child = root.getAttributeNode(elem.name)
175 165 aaronmk
        if child != None: children = [child]
176 998 aaronmk
    elif elem.name == '.': children = [root]
177 1000 aaronmk
    elif elem.name == '..':
178
        parent = xml_dom.parent(root)
179
        if parent != None: children = [parent]
180
        else: return [] # don't try to create the document root's parent
181 165 aaronmk
    else:
182 998 aaronmk
        children = xml_dom.by_tag_name(root, elem.name,
183 165 aaronmk
        last_only and (elem.keys == [] or is_instance(elem)))
184
185
    # Check each match
186 885 aaronmk
    nodes = []
187 165 aaronmk
    for child in children:
188
        is_match = elem.value == None or xml_dom.value(child) == elem.value
189
        for attr in elem.keys:
190
            if not is_match: break
191 886 aaronmk
            is_match = ((get(child, attr, False, last_only) != [])
192
                == is_positive(attr))
193 885 aaronmk
        if is_match:
194
            nodes.append(child)
195
            if limit != None and len(nodes) >= limit: break
196 165 aaronmk
197
    # Create node
198 886 aaronmk
    if nodes == []:
199
        if not create: return []
200 77 aaronmk
        if elem.is_attr:
201 998 aaronmk
            root.setAttribute(elem.name, '')
202
            node = root.getAttributeNode(elem.name)
203
        else: node = root.appendChild(doc.createElement(elem.name))
204 165 aaronmk
        if elem.value != None: xml_dom.set_value(node, elem.value)
205 886 aaronmk
        nodes.append(node)
206 165 aaronmk
207 971 aaronmk
    value_ = value(xpath)
208 165 aaronmk
    xpath = xpath[1:] # rest of XPath
209
210 886 aaronmk
    next = []
211
    for node in nodes:
212
        # Create attrs
213
        if create:
214
            for attr in elem.keys + elem.attrs:
215
                get(node, attr, create, last_only)
216
217
        # Follow pointer
218
        if elem.is_ptr:
219 998 aaronmk
            root = doc.documentElement
220 886 aaronmk
            xpath = copy.deepcopy(xpath)
221
            id_path = backward_id(xpath[instance_level])
222
            if id_path != None: # backward (child-to-parent) pointer with ID key
223
                id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
224
                set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
225
            else: # forward (parent-to-child) pointer
226
                id_ = xml_dom.value(node)
227
                obj_xpath = obj(xpath) # target object
228
                if id_ == None or get(root, obj_xpath, False, True) == []:
229
                    # no target or target keys don't match
230
                    if not create: continue
231
232
                    # Use last target object's ID + 1
233
                    obj_xpath[-1].keys = [] # just get by tag name
234
                    last = get(root, obj_xpath, False, True)
235
                    if last != []: id_ = str(int(xml_dom.get_id(last[0])) + 1)
236
                    else: id_ = '0'
237
238
                    # Will append if target keys didn't match.
239
                    # Use lookahead assertion to avoid this.
240
                    xml_dom.set_value(node, id_)
241
                else: last_only = False
242
                set_id(xpath, id_)
243
        else: root = node
244 889 aaronmk
        next += get(root, xpath, create, last_only, limit)
245 886 aaronmk
246
        for branch in elem.other_branches:
247
            branch = copy.deepcopy(branch)
248 971 aaronmk
            set_value(branch, value_)
249 889 aaronmk
            next += get(node, branch, create, last_only, limit)
250 165 aaronmk
251
    return next
252 82 aaronmk
253 141 aaronmk
def put_obj(root, xpath, id_, has_types, value=None):
254 892 aaronmk
    if util.is_str(xpath): xpath = parse(xpath)
255 155 aaronmk
256 82 aaronmk
    xpath = copy.deepcopy(xpath) # don't modify input!
257
    set_id(xpath, id_, has_types)
258 85 aaronmk
    if value != None: set_value(xpath, value)
259 141 aaronmk
    get(root, xpath, True)
260 133 aaronmk
261 135 aaronmk
def path2xml(xpath, first_branch=True):
262
    root = xml_dom.create_doc().documentElement
263 141 aaronmk
    get(root, xpath, True)
264 135 aaronmk
    return root
265 133 aaronmk
266 141 aaronmk
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)