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

    
130
instance_level = 1
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
140
    path[id_level].keys.append([XpathElem('id', id_, True)])
141

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

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

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

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

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

    
239
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(13-13/13)