Project

General

Profile

1
# XPath parsing
2

    
3
import copy
4

    
5
from Parser import Parser
6
import xml_dom
7

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

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

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

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

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

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

    
49
_cache = {}
50

    
51
def parse(str_):
52
    try: return _cache[str_]
53
    except KeyError: pass
54
    
55
    parser = Parser(str_)
56
    
57
    def _path():
58
        is_positive = not parser.str_('!')
59
        
60
        tree = []
61
        while True:
62
            # Split path
63
            if parser.str_('{'):
64
                tree[-1].other_branches = _paths()
65
                parser.str_('}', required=True)
66
                tree += tree[-1].other_branches.pop(0) # use first path for now
67
                break # nothing allowed after split path
68
            
69
            elem = XpathElem(is_attr=parser.str_('@'), name=_value())
70
            
71
            # Keys used to match nodes
72
            if parser.str_('['):
73
                elem.keys = _paths()
74
                parser.str_(']', required=True)
75
            
76
            # 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
            elem.is_ptr = parser.str_('->')
83
            tree.append(elem)
84
            
85
            # Lookahead assertion
86
            if parser.str_('('):
87
                parser.str_('/', required=True) # next / is inside ()
88
                path = _path()
89
                parser.str_(')', required=True)
90
                elem.keys.append(path)
91
                tree += path
92
            
93
            if not parser.str_('/'): break
94
        
95
        tree[0].is_positive = is_positive
96
        
97
        # Value
98
        if parser.str_('='): set_value(tree, _value())
99
        
100
        # Expand * abbrs
101
        for i in reversed(xrange(len(tree))):
102
            elem = tree[i]
103
            if elem.is_ptr: offset = 2
104
            else: offset = 1
105
            try: repl = tree[i+offset].name
106
            except IndexError: pass # no replacement elem
107
            else: elem.name = expand_abbr(elem.name, repl)
108
        
109
        return tree
110
    
111
    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
    def _paths():
119
        paths = []
120
        while True:
121
            paths.append(_path())
122
            if not parser.str_(','): break
123
        return paths
124
    
125
    path = _path()
126
    parser.end()
127
    _cache[str_] = path
128
    return path
129

    
130
instance_level = 1 # root's grandchildren
131

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

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

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

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

    
147
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
    if last_only == None: last_only = create
151
    if type(xpath) == str: xpath = parse(xpath)
152
    
153
    if xpath == []: return parent
154
    if create and not is_positive(xpath): return None
155
    doc = parent.ownerDocument
156
    root = doc.documentElement
157
    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
        if elem.is_attr:
183
            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
        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
        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

    
227
def put_obj(root, xpath, id_, has_types, value=None):
228
    if type(xpath) == str: xpath = parse(xpath)
229
    
230
    xpath = copy.deepcopy(xpath) # don't modify input!
231
    set_id(xpath, id_, has_types)
232
    if value != None: set_value(xpath, value)
233
    get(root, xpath, True)
234

    
235
def path2xml(xpath, first_branch=True):
236
    root = xml_dom.create_doc().documentElement
237
    get(root, xpath, True)
238
    return root
239

    
240
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(14-14/14)