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_('='): set_value(tree, _value())
100
        
101
        # Expand * abbrs
102
        for i in reversed(xrange(len(tree))):
103
            elem = tree[i]
104
            if elem.is_ptr: offset = 2
105
            else: offset = 1
106
            try: repl = tree[i+offset].name
107
            except IndexError: pass # no replacement elem
108
            else: elem.name = expand_abbr(elem.name, repl)
109
        
110
        return tree
111
    
112
    def _value():
113
        if parser.str_('"'):
114
            value = parser.re(r'[^"]*')
115
            parser.str_('"', required=True)
116
        else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
117
        return value
118
    
119
    def _paths():
120
        paths = []
121
        while True:
122
            paths.append(_path())
123
            if not parser.str_(','): break
124
        return paths
125
    
126
    path = _path()
127
    parser.end()
128
    _cache[str_] = path
129
    return path
130

    
131
instance_level = 1 # root's grandchildren
132

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

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

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

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

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

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

    
246
def path2xml(xpath, first_branch=True):
247
    root = xml_dom.create_doc().documentElement
248
    get(root, xpath, True)
249
    return root
250

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