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 141 aaronmk
def get(parent, xpath, create=False, last_only=None):
148
    '''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 154 aaronmk
    if type(xpath) == str: xpath = parse(xpath)
152 99 aaronmk
153 165 aaronmk
    if xpath == []: return parent
154 99 aaronmk
    if create and not is_positive(xpath): return None
155 135 aaronmk
    doc = parent.ownerDocument
156 141 aaronmk
    root = doc.documentElement
157 165 aaronmk
    elem = xpath[0]
158
159
    # Find possible matches
160
    children = []
161
    if elem.is_attr:
162
        child = parent.getAttributeNode(elem.name)
163
        if child != None: children = [child]
164
    elif elem.name == '.': children = [parent]
165
    else:
166
        children = xml_dom.by_tag_name(parent, elem.name,
167
        last_only and (elem.keys == [] or is_instance(elem)))
168
169
    # Check each match
170
    node = None
171
    for child in children:
172
        is_match = elem.value == None or xml_dom.value(child) == elem.value
173
        for attr in elem.keys:
174
            if not is_match: break
175
            is_match = (get(child, attr, False, last_only) != None)\
176
            == is_positive(attr)
177
        if is_match: node = child; break
178
179
    # Create node
180
    if node == None:
181
        if not create: return None
182 77 aaronmk
        if elem.is_attr:
183 165 aaronmk
            parent.setAttribute(elem.name, '')
184
            node = parent.getAttributeNode(elem.name)
185
        else: node = parent.appendChild(doc.createElement(elem.name))
186
        if elem.value != None: xml_dom.set_value(node, elem.value)
187
    if create:
188
        for attr in elem.keys + elem.attrs: get(node, attr, create, last_only)
189
190
    xpath = xpath[1:] # rest of XPath
191
192
    # Follow pointer
193
    if elem.is_ptr:
194
        xpath = copy.deepcopy(xpath)
195 171 aaronmk
        id_path = backward_id(xpath[instance_level])
196
        if id_path != None: # backward (child-to-parent) pointer with ID key
197
            id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
198
            set_value(id_path, xml_dom.get_id(node)) # modify id key of xpath
199 165 aaronmk
        else: # forward (parent-to-child) pointer
200
            id_ = xml_dom.value(node)
201
            obj_xpath = obj(xpath) # target object
202
            if id_ == None or get(root, obj_xpath, False, True) == None:
203
                # no target or target keys don't match
204
                if not create: return None
205
206
                # Use last target object's ID + 1
207
                obj_xpath[-1].keys = [] # just get by tag name
208
                last = get(root, obj_xpath, False, True)
209
                if last != None: id_ = str(int(xml_dom.get_id(last)) + 1)
210
                else: id_ = '0'
211
212
                # Will append if target keys didn't match.
213
                # Use lookahead assertion to avoid this.
214
                xml_dom.set_value(node, id_)
215
            else: last_only = False
216
            set_id(xpath, id_)
217
    else: root = node
218
    next = get(root, xpath, create, last_only)
219
220
    for branch in elem.other_branches:
221
        branch = copy.deepcopy(branch)
222
        set_value(branch, value(xpath))
223
        get(node, branch, create, last_only)
224
225
    return next
226 82 aaronmk
227 141 aaronmk
def put_obj(root, xpath, id_, has_types, value=None):
228 155 aaronmk
    if type(xpath) == str: xpath = parse(xpath)
229
230 82 aaronmk
    xpath = copy.deepcopy(xpath) # don't modify input!
231
    set_id(xpath, id_, has_types)
232 85 aaronmk
    if value != None: set_value(xpath, value)
233 141 aaronmk
    get(root, xpath, True)
234 133 aaronmk
235 135 aaronmk
def path2xml(xpath, first_branch=True):
236
    root = xml_dom.create_doc().documentElement
237 141 aaronmk
    get(root, xpath, True)
238 135 aaronmk
    return root
239 133 aaronmk
240 141 aaronmk
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)