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
|
def parse(str_):
|
45
|
parser = Parser(str_)
|
46
|
|
47
|
def _path():
|
48
|
is_positive = not parser.str_('!')
|
49
|
|
50
|
tree = []
|
51
|
while True:
|
52
|
# Split path
|
53
|
if parser.str_('{'):
|
54
|
tree[-1].other_branches = _paths()
|
55
|
parser.str_('}', required=True)
|
56
|
tree += tree[-1].other_branches.pop(0) # use first path for now
|
57
|
break # nothing allowed after split path
|
58
|
|
59
|
elem = XpathElem(is_attr=parser.str_('@'),
|
60
|
name=parser.re(r'[\w.*]+', required=True))
|
61
|
|
62
|
# Keys used to match nodes
|
63
|
if parser.str_('['):
|
64
|
elem.keys = _paths()
|
65
|
parser.str_(']', required=True)
|
66
|
|
67
|
# Attrs created when no matching node exists
|
68
|
if parser.str_(':'):
|
69
|
parser.str_('[', required=True)
|
70
|
elem.attrs = _paths()
|
71
|
parser.str_(']', required=True)
|
72
|
|
73
|
elem.is_ptr = parser.str_('->')
|
74
|
tree.append(elem)
|
75
|
|
76
|
# Lookahead assertion
|
77
|
if parser.str_('('):
|
78
|
parser.str_('/', required=True) # next / is inside ()
|
79
|
path = _path()
|
80
|
parser.str_(')', required=True)
|
81
|
elem.keys.append(path)
|
82
|
tree += path
|
83
|
|
84
|
if not parser.str_('/'): break
|
85
|
|
86
|
tree[0].is_positive = is_positive
|
87
|
|
88
|
# Value
|
89
|
if parser.str_('='):
|
90
|
if parser.str_('"'):
|
91
|
value = parser.re(r'[^"]*')
|
92
|
parser.str_('"', required=True)
|
93
|
else: value = parser.re(r'[\w.]*')
|
94
|
set_value(tree, value)
|
95
|
|
96
|
# Expand * abbrs
|
97
|
for i in reversed(xrange(len(tree))):
|
98
|
elem = tree[i]
|
99
|
id_ = backward_id(elem)
|
100
|
if id_ != None: elem = id_[0]; offset = -2
|
101
|
elif elem.is_ptr: offset = 2
|
102
|
else: offset = 1
|
103
|
before, abbr, after = elem.name.partition('*')
|
104
|
if abbr != '':
|
105
|
try: elem.name = before+tree[i+offset].name+after
|
106
|
except IndexError: pass # no replacement elem
|
107
|
|
108
|
return tree
|
109
|
|
110
|
def _paths():
|
111
|
paths = []
|
112
|
while True:
|
113
|
paths.append(_path())
|
114
|
if not parser.str_(','): break
|
115
|
return paths
|
116
|
|
117
|
parser.str_('/') # optional leading /
|
118
|
path = _path()
|
119
|
parser.end()
|
120
|
return path
|
121
|
|
122
|
instance_level = 1
|
123
|
|
124
|
def obj(path):
|
125
|
obj_path = copy.deepcopy(path[:instance_level+1])
|
126
|
obj_path[-1].is_ptr = False # prevent pointer w/o target
|
127
|
return obj_path
|
128
|
|
129
|
def set_id(path, id_, has_types=True):
|
130
|
if has_types: id_level = instance_level
|
131
|
else: id_level = 0
|
132
|
path[id_level].keys.append([XpathElem('id', id_, True)])
|
133
|
|
134
|
def is_id(path): return path[0].is_attr and path[0].name == 'id'
|
135
|
|
136
|
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
|
137
|
|
138
|
def get(parent, xpath, create=False, last_only=None):
|
139
|
'''Warning: The last_only optimization may put data that should be together
|
140
|
into separate nodes'''
|
141
|
if last_only == None: last_only = create
|
142
|
|
143
|
if create and not is_positive(xpath): return None
|
144
|
doc = parent.ownerDocument
|
145
|
root = doc.documentElement
|
146
|
for elem_idx, elem in enumerate(xpath):
|
147
|
# Find possible matches
|
148
|
children = []
|
149
|
if elem.is_attr:
|
150
|
child = parent.getAttributeNode(elem.name)
|
151
|
if child != None: children = [child]
|
152
|
elif elem.name == '.': children = [parent]
|
153
|
else:
|
154
|
children = xml_dom.by_tag_name(parent, elem.name,
|
155
|
last_only and (elem.keys == [] or is_instance(elem)))
|
156
|
|
157
|
# Check each match
|
158
|
node = None
|
159
|
for child in children:
|
160
|
is_match = elem.value == None or xml_dom.value(child) == elem.value
|
161
|
for attr in elem.keys:
|
162
|
if not is_match: break
|
163
|
is_match = (get(child, attr, False, last_only) != None)\
|
164
|
== is_positive(attr)
|
165
|
if is_match: node = child; break
|
166
|
|
167
|
# Create node
|
168
|
if node == None:
|
169
|
if not create: return None
|
170
|
if elem.is_attr:
|
171
|
parent.setAttribute(elem.name, '')
|
172
|
node = parent.getAttributeNode(elem.name)
|
173
|
else: node = parent.appendChild(doc.createElement(elem.name))
|
174
|
if elem.value != None: xml_dom.set_value(node, elem.value)
|
175
|
if create:
|
176
|
for attr in elem.keys + elem.attrs:
|
177
|
get(node, attr, create, last_only)
|
178
|
|
179
|
for branch in elem.other_branches:
|
180
|
branch = copy.deepcopy(branch)
|
181
|
set_value(branch, value(xpath))
|
182
|
get(node, branch, create, last_only)
|
183
|
|
184
|
# Follow pointer
|
185
|
if elem.is_ptr:
|
186
|
xpath = copy.deepcopy(xpath[elem_idx+1:]) # rest of XPath
|
187
|
id_elem = backward_id(xpath[instance_level])
|
188
|
if id_elem != None:
|
189
|
# backward (child-to-parent) pointer with target ID attr
|
190
|
set_value(id_elem, xml_dom.get_id(node))
|
191
|
else: # forward (parent-to-child) pointer
|
192
|
id_ = xml_dom.value(node)
|
193
|
obj_xpath = obj(xpath) # target object
|
194
|
if id_ == None or get(root, obj_xpath, False, True) == None:
|
195
|
# no target or target keys don't match
|
196
|
if not create: return None
|
197
|
|
198
|
# Use last target object's ID + 1
|
199
|
obj_xpath[-1].keys = [] # just get by tag name
|
200
|
last = get(root, obj_xpath, False, True)
|
201
|
if last != None: id_ = str(int(xml_dom.get_id(last)) + 1)
|
202
|
else: id_ = '0'
|
203
|
|
204
|
# Will append if target keys didn't match. Place ! in XPath
|
205
|
# after element to fork at to avoid this.
|
206
|
xml_dom.set_value(node, id_)
|
207
|
else: last_only = False
|
208
|
set_id(xpath, id_)
|
209
|
return get(root, xpath, create, last_only)
|
210
|
|
211
|
parent = node
|
212
|
return parent
|
213
|
|
214
|
def put_obj(root, xpath, id_, has_types, value=None):
|
215
|
xpath = copy.deepcopy(xpath) # don't modify input!
|
216
|
set_id(xpath, id_, has_types)
|
217
|
if value != None: set_value(xpath, value)
|
218
|
get(root, xpath, True)
|
219
|
|
220
|
def path2xml(xpath, first_branch=True):
|
221
|
root = xml_dom.create_doc().documentElement
|
222
|
get(root, xpath, True)
|
223
|
return root
|
224
|
|
225
|
def str2xml(xpath): return path2xml(parse(xpath))
|
226
|
|
227
|
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
|