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