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

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

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

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

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

    
44
_cache = {}
45

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

    
128
instance_level = 1
129

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

    
135
def set_id(path, id_, has_types=True):
136
    if has_types: id_level = instance_level
137
    else: id_level = 0
138
    path[id_level].keys.append([XpathElem('id', id_, True)])
139

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

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

    
144
def get(parent, xpath, create=False, last_only=None):
145
    '''Warning: The last_only optimization may put data that should be together
146
    into separate nodes'''
147
    if last_only == None: last_only = create
148
    if type(xpath) == str: xpath = parse(xpath)
149
    
150
    if create and not is_positive(xpath): return None
151
    doc = parent.ownerDocument
152
    root = doc.documentElement
153
    for elem_idx, elem in enumerate(xpath):
154
        # Find possible matches
155
        children = []
156
        if elem.is_attr:
157
            child = parent.getAttributeNode(elem.name)
158
            if child != None: children = [child]
159
        elif elem.name == '.': children = [parent]
160
        else:
161
            children = xml_dom.by_tag_name(parent, elem.name,
162
            last_only and (elem.keys == [] or is_instance(elem)))
163
        
164
        # Check each match
165
        node = None
166
        for child in children:
167
            is_match = elem.value == None or xml_dom.value(child) == elem.value
168
            for attr in elem.keys:
169
                if not is_match: break
170
                is_match = (get(child, attr, False, last_only) != None)\
171
                == is_positive(attr)
172
            if is_match: node = child; break
173
        
174
        # Create node
175
        if node == None:
176
            if not create: return None
177
            if elem.is_attr:
178
                parent.setAttribute(elem.name, '')
179
                node = parent.getAttributeNode(elem.name)
180
            else: node = parent.appendChild(doc.createElement(elem.name))
181
            if elem.value != None: xml_dom.set_value(node, elem.value)
182
        if create:
183
            for attr in elem.keys + elem.attrs:
184
                get(node, attr, create, last_only)
185
        
186
        for branch in elem.other_branches:
187
            branch = copy.deepcopy(branch)
188
            set_value(branch, value(xpath))
189
            get(node, branch, create, last_only)
190
        
191
        # Follow pointer
192
        if elem.is_ptr:
193
            xpath = copy.deepcopy(xpath[elem_idx+1:]) # rest of XPath
194
            id_elem = backward_id(xpath[instance_level])
195
            if id_elem != None:
196
                # backward (child-to-parent) pointer with target ID attr
197
                set_value(id_elem, xml_dom.get_id(node))
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. Place ! in XPath
212
                    # after element to fork at to avoid this.
213
                    xml_dom.set_value(node, id_)
214
                else: last_only = False
215
                set_id(xpath, id_)
216
            return get(root, xpath, create, last_only)
217
        
218
        parent = node
219
    return parent
220

    
221
def put_obj(root, xpath, id_, has_types, value=None):
222
    if type(xpath) == str: xpath = parse(xpath)
223
    
224
    xpath = copy.deepcopy(xpath) # don't modify input!
225
    set_id(xpath, id_, has_types)
226
    if value != None: set_value(xpath, value)
227
    get(root, xpath, True)
228

    
229
def path2xml(xpath, first_branch=True):
230
    root = xml_dom.create_doc().documentElement
231
    get(root, xpath, True)
232
    return root
233

    
234
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
(11-11/11)