Project

General

Profile

1
# XPath parsing
2

    
3
import copy
4

    
5
from Parser import Parser
6
import util
7
import xml_dom
8

    
9
##### Path elements
10

    
11
class XpathElem:
12
    def __init__(self, name, value=None, is_attr=False):
13
        if name == '': name = '.'
14
        self.name = name
15
        self.value = value
16
        self.is_attr = is_attr
17
        self.is_positive = True
18
        self.is_ptr = False
19
        self.keys = []
20
        self.attrs = []
21
        self.other_branches = [] # temp implementation for split paths
22
    
23
    def __repr__(self):
24
        str_ = ''
25
        if not self.is_positive: str_ += '!'
26
        if self.is_attr: str_ += '@'
27
        str_ += self.name
28
        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
        if self.value != None: str_ += '='+repr(self.value)
33
        return str_
34
    
35
    def __eq__(self, other): return self.__dict__ == other.__dict__
36

    
37
##### Paths
38

    
39
def is_positive(path): return path[0].is_positive
40

    
41
def value(path): return path[-1].value
42

    
43
def set_value(path, value): path[-1].value = value
44

    
45
def backward_id(elem):
46
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
47
    else: return None
48

    
49
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
def expand_abbr(name, repl):
69
    before, abbr, after = name.partition('*')
70
    if abbr != '': name = before+repl+after
71
    return name
72

    
73
_cache = {}
74

    
75
def parse(str_):
76
    try: return _cache[str_]
77
    except KeyError: pass
78
    
79
    parser = Parser(str_)
80
    
81
    def _path():
82
        is_positive = not parser.str_('!')
83
        
84
        tree = []
85
        while True:
86
            # Split path
87
            if parser.str_('{'):
88
                tree[-1].other_branches = _paths()
89
                parser.str_('}', required=True)
90
                tree += tree[-1].other_branches.pop(0) # use first path for now
91
                break # nothing allowed after split path
92
            
93
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
94
            
95
            # Keys used to match nodes
96
            if parser.str_('['):
97
                elem.keys = _paths()
98
                parser.str_(']', required=True)
99
            
100
            # 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
            elem.is_ptr = parser.str_('->')
107
            tree.append(elem)
108
            
109
            # Lookahead assertion
110
            if parser.str_('('):
111
                parser.str_('/', required=True) # next / is inside ()
112
                path = _path()
113
                parser.str_(')', required=True)
114
                elem.keys.append(path)
115
                tree += path
116
            
117
            if not parser.str_('/'): break
118
        
119
        tree[0].is_positive = is_positive
120
        
121
        # Value
122
        if parser.str_('='):
123
            if parser.str_('$'): value = _path()
124
            else: value = _value()
125
            set_value(tree, value)
126
        
127
        # Expand * abbrs
128
        for i in reversed(xrange(len(tree))):
129
            elem = tree[i]
130
            if elem.is_ptr: offset = 2
131
            else: offset = 1
132
            try: repl = tree[i+offset].name
133
            except IndexError: pass # no replacement elem
134
            else: elem.name = expand_abbr(elem.name, repl)
135
        
136
        return tree
137
    
138
    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
    def _paths():
146
        paths = []
147
        while True:
148
            paths.append(_path())
149
            if not parser.str_(','): break
150
        return paths
151
    
152
    path = _path()
153
    parser.end()
154
    _cache[str_] = path
155
    return path
156

    
157
##### Querying/creating XML trees
158

    
159
def get(root, xpath, create=False, last_only=None, limit=1):
160
    '''Warning: The last_only optimization may put data that should be together
161
    into separate nodes'''
162
    if last_only == None: last_only = create
163
    if limit == None or limit > 1: last_only = False
164
    if util.is_str(xpath): xpath = parse(xpath)
165
    
166
    if xpath == []: return [root]
167
    if create and not is_positive(xpath): return []
168
    doc = root.ownerDocument
169
    elem = xpath[0]
170
    
171
    # Find possible matches
172
    children = []
173
    if elem.is_attr:
174
        child = root.getAttributeNode(elem.name)
175
        if child != None: children = [child]
176
    elif elem.name == '.': children = [root]
177
    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
    else:
182
        children = xml_dom.by_tag_name(root, elem.name,
183
        last_only and (elem.keys == [] or is_instance(elem)))
184
    
185
    # Check each match
186
    nodes = []
187
    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
            is_match = ((get(child, attr, False, last_only) != [])
192
                == is_positive(attr))
193
        if is_match:
194
            nodes.append(child)
195
            if limit != None and len(nodes) >= limit: break
196
    
197
    # Create node
198
    if nodes == []:
199
        if not create: return []
200
        if elem.is_attr:
201
            root.setAttribute(elem.name, '')
202
            node = root.getAttributeNode(elem.name)
203
        else: node = root.appendChild(doc.createElement(elem.name))
204
        if elem.value != None: xml_dom.set_value(node, elem.value)
205
        nodes.append(node)
206
    
207
    value_ = value(xpath)
208
    xpath = xpath[1:] # rest of XPath
209
    
210
    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
            root = doc.documentElement
220
            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
        next += get(root, xpath, create, last_only, limit)
245
        
246
        for branch in elem.other_branches:
247
            branch = copy.deepcopy(branch)
248
            set_value(branch, value_)
249
            next += get(node, branch, create, last_only, limit)
250
    
251
    return next
252

    
253
def put_obj(root, xpath, id_, has_types, value=None):
254
    if util.is_str(xpath): xpath = parse(xpath)
255
    
256
    xpath = copy.deepcopy(xpath) # don't modify input!
257
    set_id(xpath, id_, has_types)
258
    if value != None: set_value(xpath, value)
259
    get(root, xpath, True)
260

    
261
def path2xml(xpath, first_branch=True):
262
    root = xml_dom.create_doc().documentElement
263
    get(root, xpath, True)
264
    return root
265

    
266
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(16-16/16)