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

    
31
def value(path): return path[-1].value
32

    
33
def set_value(path, value): path[-1].value = value
34

    
35
def backward_id(elem):
36
    if len(elem.keys) >= 1 and value(elem.keys[0]) == None and\
37
    len(elem.keys[0]) == 1: return elem.keys[0]
38
    else: return None
39

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

    
113
instance_level = 1
114

    
115
def obj(path):
116
    obj_path = copy.deepcopy(path[:instance_level+1])
117
    obj_path[-1].is_ptr = False # prevent pointer w/o target
118
    return obj_path
119

    
120
def set_id(path, id_, has_types=True):
121
    if has_types: id_level = instance_level
122
    else: id_level = 0
123
    path[id_level].keys.append([XpathElem('id', id_, True)])
124

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

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

    
129
def get(doc, xpath, create=False, last_only=None, parent=None):
130
    # Warning: The last_only optimization may put data that should be together
131
    # into separate nodes
132
    if parent == None: parent = doc.documentElement
133
    if last_only == None: last_only = create
134
    for elem_idx, elem in enumerate(xpath):
135
        # Find possible matches
136
        children = []
137
        if elem.is_attr:
138
            child = parent.getAttributeNode(elem.name)
139
            if child != None: children = [child]
140
        elif elem.name == '.': children = [parent]
141
        else:
142
            children = xml_dom.by_tag_name(parent, elem.name,
143
            last_only and (elem.keys == [] or is_instance(elem)))
144
        
145
        # Check each match
146
        node = None
147
        for child in children:
148
            is_match = elem.value == None or xml_dom.value(child) == elem.value
149
            for attr in elem.keys:
150
                if not is_match: break
151
                is_match = get(doc, attr, False, last_only, child) != None
152
            if is_match: node = child; break
153
        
154
        # Create node
155
        if node == None:
156
            if not create: return None
157
            if elem.is_attr:
158
                parent.setAttribute(elem.name, '')
159
                node = parent.getAttributeNode(elem.name)
160
            else: node = parent.appendChild(doc.createElement(elem.name))
161
            if elem.value != None: xml_dom.set_value(doc, node, elem.value)
162
            for attr in elem.keys + elem.attrs:
163
                get(doc, attr, create, last_only, node)
164
        
165
        for branch in elem.other_branches:
166
            branch = copy.deepcopy(branch)
167
            set_value(branch, value(xpath))
168
            get(doc, branch, create, last_only, node)
169
        
170
        # Follow pointer
171
        if elem.is_ptr:
172
            xpath = copy.deepcopy(xpath[elem_idx+1:]) # rest of XPath
173
            id_elem = backward_id(xpath[instance_level])
174
            if id_elem != None:
175
                # backward (child-to-parent) pointer with target ID attr
176
                set_value(id_elem, xml_dom.get_id(node))
177
            else: # forward (parent-to-child) pointer
178
                id_ = xml_dom.value(node)
179
                obj_xpath = obj(xpath) # target object
180
                if id_ == None or get(doc, obj_xpath, False, True) == None:
181
                    # no target or target keys don't match
182
                    if not create: return None
183
                    
184
                    # Use last target object's ID + 1
185
                    obj_xpath[-1].keys = [] # just get by tag name
186
                    last = get(doc, obj_xpath, False, True)
187
                    if last != None: id_ = str(int(xml_dom.get_id(last)) + 1)
188
                    else: id_ = '0'
189
                    
190
                    # Will append if target keys didn't match. Place ! in XPath
191
                    # after element to fork at to avoid this.
192
                    xml_dom.set_value(doc, node, id_)
193
                else: last_only = False
194
                set_id(xpath, id_)
195
            return get(doc, xpath, create, last_only)
196
        
197
        parent = node
198
    return parent
199

    
200
def put_obj(doc, xpath, id_, has_types, value=None):
201
    xpath = copy.deepcopy(xpath) # don't modify input!
202
    set_id(xpath, id_, has_types)
203
    if value != None: set_value(xpath, value)
204
    get(doc, xpath, True)
(10-10/10)