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

    
35
def is_positive(path): return path[0].is_positive
36

    
37
def value(path): return path[-1].value
38

    
39
def set_value(path, value): path[-1].value = value
40

    
41
def backward_id(elem):
42
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
43
    else: return None
44

    
45
def expand_abbr(name, repl):
46
    before, abbr, after = name.partition('*')
47
    if abbr != '': name = before+repl+after
48
    return name
49

    
50
_cache = {}
51

    
52
def parse(str_):
53
    try: return _cache[str_]
54
    except KeyError: pass
55
    
56
    parser = Parser(str_)
57
    
58
    def _path():
59
        is_positive = not parser.str_('!')
60
        
61
        tree = []
62
        while True:
63
            # Split path
64
            if parser.str_('{'):
65
                tree[-1].other_branches = _paths()
66
                parser.str_('}', required=True)
67
                tree += tree[-1].other_branches.pop(0) # use first path for now
68
                break # nothing allowed after split path
69
            
70
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
71
            
72
            # Keys used to match nodes
73
            if parser.str_('['):
74
                elem.keys = _paths()
75
                parser.str_(']', required=True)
76
            
77
            # Attrs created when no matching node exists
78
            if parser.str_(':'):
79
                parser.str_('[', required=True)
80
                elem.attrs = _paths()
81
                parser.str_(']', required=True)
82
            
83
            elem.is_ptr = parser.str_('->')
84
            tree.append(elem)
85
            
86
            # Lookahead assertion
87
            if parser.str_('('):
88
                parser.str_('/', required=True) # next / is inside ()
89
                path = _path()
90
                parser.str_(')', required=True)
91
                elem.keys.append(path)
92
                tree += path
93
            
94
            if not parser.str_('/'): break
95
        
96
        tree[0].is_positive = is_positive
97
        
98
        # Value
99
        if parser.str_('='):
100
            if parser.str_('$'): value = _path()
101
            else: value = _value()
102
            set_value(tree, value)
103
        
104
        # Expand * abbrs
105
        for i in reversed(xrange(len(tree))):
106
            elem = tree[i]
107
            if elem.is_ptr: offset = 2
108
            else: offset = 1
109
            try: repl = tree[i+offset].name
110
            except IndexError: pass # no replacement elem
111
            else: elem.name = expand_abbr(elem.name, repl)
112
        
113
        return tree
114
    
115
    def _value():
116
        if parser.str_('"'):
117
            value = parser.re(r'[^"]*')
118
            parser.str_('"', required=True)
119
        else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
120
        return value
121
    
122
    def _paths():
123
        paths = []
124
        while True:
125
            paths.append(_path())
126
            if not parser.str_(','): break
127
        return paths
128
    
129
    path = _path()
130
    parser.end()
131
    _cache[str_] = path
132
    return path
133

    
134
instance_level = 1 # root's grandchildren
135

    
136
def obj(path):
137
    obj_path = copy.deepcopy(path[:instance_level+1])
138
    obj_path[-1].is_ptr = False # prevent pointer w/o target
139
    return obj_path
140

    
141
def set_id(path, id_, has_types=True):
142
    if has_types: id_level = instance_level
143
    else: id_level = 0 # root's children
144
    if path[0].name == '.': id_level += 1 # explicit root element
145
    path[id_level].keys.append([XpathElem('id', id_, True)])
146

    
147
def is_id(path): return path[0].is_attr and path[0].name == 'id'
148

    
149
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0]) 
150

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

    
241
def put_obj(root, xpath, id_, has_types, value=None):
242
    if util.is_str(xpath): xpath = parse(xpath)
243
    
244
    xpath = copy.deepcopy(xpath) # don't modify input!
245
    set_id(xpath, id_, has_types)
246
    if value != None: set_value(xpath, value)
247
    get(root, xpath, True)
248

    
249
def path2xml(xpath, first_branch=True):
250
    root = xml_dom.create_doc().documentElement
251
    get(root, xpath, True)
252
    return root
253

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