1 |
55
|
aaronmk
|
# XPath parsing
|
2 |
21
|
aaronmk
|
|
3 |
55
|
aaronmk
|
import copy
|
4 |
21
|
aaronmk
|
|
5 |
|
|
from Parser import Parser
|
6 |
77
|
aaronmk
|
import xml_dom
|
7 |
21
|
aaronmk
|
|
8 |
|
|
class XpathElem:
|
9 |
94
|
aaronmk
|
def __init__(self, name, value=None, is_attr=False):
|
10 |
21
|
aaronmk
|
self.name = name
|
11 |
|
|
self.value = value
|
12 |
|
|
self.is_attr = is_attr
|
13 |
97
|
aaronmk
|
self.is_positive = True
|
14 |
94
|
aaronmk
|
self.is_ptr = False
|
15 |
|
|
self.keys = []
|
16 |
|
|
self.attrs = []
|
17 |
78
|
aaronmk
|
self.other_branches = [] # temp implementation for split paths
|
18 |
21
|
aaronmk
|
|
19 |
|
|
def __repr__(self):
|
20 |
|
|
str_ = ''
|
21 |
141
|
aaronmk
|
if not self.is_positive: str_ += '!'
|
22 |
21
|
aaronmk
|
if self.is_attr: str_ += '@'
|
23 |
25
|
aaronmk
|
str_ += self.name
|
24 |
94
|
aaronmk
|
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 |
25
|
aaronmk
|
if self.value != None: str_ += '='+repr(self.value)
|
29 |
21
|
aaronmk
|
return str_
|
30 |
|
|
|
31 |
|
|
def __eq__(self, other): return self.__dict__ == other.__dict__
|
32 |
|
|
|
33 |
99
|
aaronmk
|
def is_positive(path): return path[0].is_positive
|
34 |
|
|
|
35 |
24
|
aaronmk
|
def value(path): return path[-1].value
|
36 |
|
|
|
37 |
22
|
aaronmk
|
def set_value(path, value): path[-1].value = value
|
38 |
|
|
|
39 |
32
|
aaronmk
|
def backward_id(elem):
|
40 |
94
|
aaronmk
|
if len(elem.keys) >= 1 and value(elem.keys[0]) == None and\
|
41 |
|
|
len(elem.keys[0]) == 1: return elem.keys[0]
|
42 |
32
|
aaronmk
|
else: return None
|
43 |
|
|
|
44 |
76
|
aaronmk
|
def parse(str_):
|
45 |
|
|
parser = Parser(str_)
|
46 |
21
|
aaronmk
|
|
47 |
76
|
aaronmk
|
def _path():
|
48 |
97
|
aaronmk
|
is_positive = not parser.str_('!')
|
49 |
|
|
|
50 |
21
|
aaronmk
|
tree = []
|
51 |
|
|
while True:
|
52 |
38
|
aaronmk
|
# Split path
|
53 |
76
|
aaronmk
|
if parser.str_('{'):
|
54 |
94
|
aaronmk
|
tree[-1].other_branches = _paths()
|
55 |
76
|
aaronmk
|
parser.str_('}', required=True)
|
56 |
94
|
aaronmk
|
tree += tree[-1].other_branches.pop(0) # use first path for now
|
57 |
38
|
aaronmk
|
break # nothing allowed after split path
|
58 |
36
|
aaronmk
|
|
59 |
76
|
aaronmk
|
elem = XpathElem(is_attr=parser.str_('@'),
|
60 |
|
|
name=parser.re(r'[\w.*]+', required=True))
|
61 |
38
|
aaronmk
|
|
62 |
94
|
aaronmk
|
# Keys used to match nodes
|
63 |
76
|
aaronmk
|
if parser.str_('['):
|
64 |
94
|
aaronmk
|
elem.keys = _paths()
|
65 |
76
|
aaronmk
|
parser.str_(']', required=True)
|
66 |
36
|
aaronmk
|
|
67 |
94
|
aaronmk
|
# 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 |
76
|
aaronmk
|
elem.is_ptr = parser.str_('->')
|
74 |
21
|
aaronmk
|
tree.append(elem)
|
75 |
36
|
aaronmk
|
|
76 |
|
|
# Lookahead assertion
|
77 |
76
|
aaronmk
|
if parser.str_('('):
|
78 |
|
|
parser.str_('/', required=True) # next / is inside ()
|
79 |
|
|
path = _path()
|
80 |
|
|
parser.str_(')', required=True)
|
81 |
94
|
aaronmk
|
elem.keys.append(path)
|
82 |
36
|
aaronmk
|
tree += path
|
83 |
|
|
|
84 |
76
|
aaronmk
|
if not parser.str_('/'): break
|
85 |
32
|
aaronmk
|
|
86 |
97
|
aaronmk
|
tree[0].is_positive = is_positive
|
87 |
|
|
|
88 |
|
|
# Value
|
89 |
91
|
aaronmk
|
if parser.str_('='):
|
90 |
|
|
if parser.str_('"'):
|
91 |
|
|
value = parser.re(r'[^"]*')
|
92 |
|
|
parser.str_('"', required=True)
|
93 |
92
|
aaronmk
|
else: value = parser.re(r'[\w.]*')
|
94 |
91
|
aaronmk
|
set_value(tree, value)
|
95 |
85
|
aaronmk
|
|
96 |
32
|
aaronmk
|
# Expand * abbrs
|
97 |
70
|
aaronmk
|
for i in reversed(xrange(len(tree))):
|
98 |
|
|
elem = tree[i]
|
99 |
32
|
aaronmk
|
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 |
70
|
aaronmk
|
try: elem.name = before+tree[i+offset].name+after
|
106 |
32
|
aaronmk
|
except IndexError: pass # no replacement elem
|
107 |
|
|
|
108 |
21
|
aaronmk
|
return tree
|
109 |
76
|
aaronmk
|
|
110 |
94
|
aaronmk
|
def _paths():
|
111 |
|
|
paths = []
|
112 |
|
|
while True:
|
113 |
|
|
paths.append(_path())
|
114 |
|
|
if not parser.str_(','): break
|
115 |
|
|
return paths
|
116 |
|
|
|
117 |
76
|
aaronmk
|
parser.str_('/') # optional leading /
|
118 |
|
|
path = _path()
|
119 |
|
|
parser.end()
|
120 |
|
|
return path
|
121 |
21
|
aaronmk
|
|
122 |
26
|
aaronmk
|
instance_level = 1
|
123 |
22
|
aaronmk
|
|
124 |
26
|
aaronmk
|
def obj(path):
|
125 |
55
|
aaronmk
|
obj_path = copy.deepcopy(path[:instance_level+1])
|
126 |
26
|
aaronmk
|
obj_path[-1].is_ptr = False # prevent pointer w/o target
|
127 |
|
|
return obj_path
|
128 |
|
|
|
129 |
22
|
aaronmk
|
def set_id(path, id_, has_types=True):
|
130 |
26
|
aaronmk
|
if has_types: id_level = instance_level
|
131 |
21
|
aaronmk
|
else: id_level = 0
|
132 |
94
|
aaronmk
|
path[id_level].keys.append([XpathElem('id', id_, True)])
|
133 |
62
|
aaronmk
|
|
134 |
|
|
def is_id(path): return path[0].is_attr and path[0].name == 'id'
|
135 |
|
|
|
136 |
94
|
aaronmk
|
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
|
137 |
77
|
aaronmk
|
|
138 |
141
|
aaronmk
|
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 |
77
|
aaronmk
|
if last_only == None: last_only = create
|
142 |
99
|
aaronmk
|
|
143 |
|
|
if create and not is_positive(xpath): return None
|
144 |
135
|
aaronmk
|
doc = parent.ownerDocument
|
145 |
141
|
aaronmk
|
root = doc.documentElement
|
146 |
83
|
aaronmk
|
for elem_idx, elem in enumerate(xpath):
|
147 |
77
|
aaronmk
|
# 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 |
94
|
aaronmk
|
last_only and (elem.keys == [] or is_instance(elem)))
|
156 |
77
|
aaronmk
|
|
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 |
94
|
aaronmk
|
for attr in elem.keys:
|
162 |
77
|
aaronmk
|
if not is_match: break
|
163 |
141
|
aaronmk
|
is_match = (get(child, attr, False, last_only) != None)\
|
164 |
99
|
aaronmk
|
== is_positive(attr)
|
165 |
77
|
aaronmk
|
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 |
143
|
aaronmk
|
if elem.value != None: xml_dom.set_value(node, elem.value)
|
175 |
95
|
aaronmk
|
if create:
|
176 |
94
|
aaronmk
|
for attr in elem.keys + elem.attrs:
|
177 |
141
|
aaronmk
|
get(node, attr, create, last_only)
|
178 |
77
|
aaronmk
|
|
179 |
78
|
aaronmk
|
for branch in elem.other_branches:
|
180 |
81
|
aaronmk
|
branch = copy.deepcopy(branch)
|
181 |
78
|
aaronmk
|
set_value(branch, value(xpath))
|
182 |
141
|
aaronmk
|
get(node, branch, create, last_only)
|
183 |
78
|
aaronmk
|
|
184 |
77
|
aaronmk
|
# 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 |
141
|
aaronmk
|
if id_ == None or get(root, obj_xpath, False, True) == None:
|
195 |
94
|
aaronmk
|
# no target or target keys don't match
|
196 |
77
|
aaronmk
|
if not create: return None
|
197 |
|
|
|
198 |
|
|
# Use last target object's ID + 1
|
199 |
94
|
aaronmk
|
obj_xpath[-1].keys = [] # just get by tag name
|
200 |
141
|
aaronmk
|
last = get(root, obj_xpath, False, True)
|
201 |
77
|
aaronmk
|
if last != None: id_ = str(int(xml_dom.get_id(last)) + 1)
|
202 |
|
|
else: id_ = '0'
|
203 |
|
|
|
204 |
94
|
aaronmk
|
# Will append if target keys didn't match. Place ! in XPath
|
205 |
77
|
aaronmk
|
# after element to fork at to avoid this.
|
206 |
143
|
aaronmk
|
xml_dom.set_value(node, id_)
|
207 |
77
|
aaronmk
|
else: last_only = False
|
208 |
|
|
set_id(xpath, id_)
|
209 |
141
|
aaronmk
|
return get(root, xpath, create, last_only)
|
210 |
77
|
aaronmk
|
|
211 |
|
|
parent = node
|
212 |
|
|
return parent
|
213 |
82
|
aaronmk
|
|
214 |
141
|
aaronmk
|
def put_obj(root, xpath, id_, has_types, value=None):
|
215 |
82
|
aaronmk
|
xpath = copy.deepcopy(xpath) # don't modify input!
|
216 |
|
|
set_id(xpath, id_, has_types)
|
217 |
85
|
aaronmk
|
if value != None: set_value(xpath, value)
|
218 |
141
|
aaronmk
|
get(root, xpath, True)
|
219 |
133
|
aaronmk
|
|
220 |
135
|
aaronmk
|
def path2xml(xpath, first_branch=True):
|
221 |
|
|
root = xml_dom.create_doc().documentElement
|
222 |
141
|
aaronmk
|
get(root, xpath, True)
|
223 |
135
|
aaronmk
|
return root
|
224 |
133
|
aaronmk
|
|
225 |
|
|
def str2xml(xpath): return path2xml(parse(xpath))
|
226 |
141
|
aaronmk
|
|
227 |
|
|
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
|