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, attrs=None, is_attr=False,
|
10
|
is_ptr=False):
|
11
|
if attrs == None: attrs = []
|
12
|
self.name = name
|
13
|
self.value = value
|
14
|
self.attrs = attrs
|
15
|
self.is_attr = is_attr
|
16
|
self.is_ptr = is_ptr
|
17
|
self.other_branches = [] # temp implementation for split paths
|
18
|
|
19
|
def __repr__(self):
|
20
|
str_ = ''
|
21
|
if self.is_attr: str_ += '@'
|
22
|
str_ += self.name
|
23
|
if self.attrs != []: str_ += repr(self.attrs)
|
24
|
if self.value != None: str_ += '='+repr(self.value)
|
25
|
if self.is_ptr: str_ += '->'
|
26
|
return str_
|
27
|
|
28
|
def __eq__(self, other): return self.__dict__ == other.__dict__
|
29
|
|
30
|
def value(path): return path[-1].value
|
31
|
|
32
|
def set_value(path, value): path[-1].value = value
|
33
|
|
34
|
def backward_id(elem):
|
35
|
if len(elem.attrs) >= 1 and value(elem.attrs[0]) == None and\
|
36
|
len(elem.attrs[0]) == 1: return elem.attrs[0]
|
37
|
else: return None
|
38
|
|
39
|
def parse(str_):
|
40
|
parser = Parser(str_)
|
41
|
|
42
|
def _path():
|
43
|
tree = []
|
44
|
while True:
|
45
|
# Split path
|
46
|
if parser.str_('{'):
|
47
|
paths = tree[-1].other_branches
|
48
|
while True:
|
49
|
paths.append(_path())
|
50
|
if not parser.str_(','): break
|
51
|
parser.str_('}', required=True)
|
52
|
tree += paths.pop(0) # use first subpath for now
|
53
|
break # nothing allowed after split path
|
54
|
|
55
|
elem = XpathElem(is_attr=parser.str_('@'),
|
56
|
name=parser.re(r'[\w.*]+', required=True))
|
57
|
|
58
|
# Attrs
|
59
|
if parser.str_('['):
|
60
|
while True:
|
61
|
elem.attrs.append(_path())
|
62
|
if not parser.str_(','): break
|
63
|
parser.str_(']', required=True)
|
64
|
|
65
|
elem.is_ptr = parser.str_('->')
|
66
|
tree.append(elem)
|
67
|
|
68
|
# Lookahead assertion
|
69
|
if parser.str_('('):
|
70
|
parser.str_('/', required=True) # next / is inside ()
|
71
|
path = _path()
|
72
|
parser.str_(')', required=True)
|
73
|
elem.attrs.append(path)
|
74
|
tree += path
|
75
|
|
76
|
if not parser.str_('/'): break
|
77
|
|
78
|
if parser.str_('='): set_value(tree, parser.re(r'[\w.|]*'))
|
79
|
|
80
|
# Expand * abbrs
|
81
|
for i in reversed(xrange(len(tree))):
|
82
|
elem = tree[i]
|
83
|
id_ = backward_id(elem)
|
84
|
if id_ != None: elem = id_[0]; offset = -2
|
85
|
elif elem.is_ptr: offset = 2
|
86
|
else: offset = 1
|
87
|
before, abbr, after = elem.name.partition('*')
|
88
|
if abbr != '':
|
89
|
try: elem.name = before+tree[i+offset].name+after
|
90
|
except IndexError: pass # no replacement elem
|
91
|
|
92
|
return tree
|
93
|
|
94
|
parser.str_('/') # optional leading /
|
95
|
path = _path()
|
96
|
parser.end()
|
97
|
return path
|
98
|
|
99
|
instance_level = 1
|
100
|
|
101
|
def obj(path):
|
102
|
obj_path = copy.deepcopy(path[:instance_level+1])
|
103
|
obj_path[-1].is_ptr = False # prevent pointer w/o target
|
104
|
return obj_path
|
105
|
|
106
|
def set_id(path, id_, has_types=True):
|
107
|
if has_types: id_level = instance_level
|
108
|
else: id_level = 0
|
109
|
path[id_level].attrs.append([XpathElem('id', id_, is_attr=True)])
|
110
|
|
111
|
def is_id(path): return path[0].is_attr and path[0].name == 'id'
|
112
|
|
113
|
def is_instance(elem): return elem.attrs != [] and is_id(elem.attrs[0])
|
114
|
|
115
|
def get(doc, xpath, create=False, last_only=None, parent=None):
|
116
|
# Warning: The last_only optimization may put data that should be together
|
117
|
# into separate nodes
|
118
|
if parent == None: parent = doc.documentElement
|
119
|
if last_only == None: last_only = create
|
120
|
for elem_idx, elem in enumerate(xpath):
|
121
|
# Find possible matches
|
122
|
children = []
|
123
|
if elem.is_attr:
|
124
|
child = parent.getAttributeNode(elem.name)
|
125
|
if child != None: children = [child]
|
126
|
elif elem.name == '.': children = [parent]
|
127
|
else:
|
128
|
children = xml_dom.by_tag_name(parent, elem.name,
|
129
|
last_only and (elem.attrs == [] or is_instance(elem)))
|
130
|
|
131
|
# Check each match
|
132
|
node = None
|
133
|
for child in children:
|
134
|
is_match = elem.value == None or xml_dom.value(child) == elem.value
|
135
|
for attr in elem.attrs:
|
136
|
if not is_match: break
|
137
|
is_match = get(doc, attr, False, last_only, child) != None
|
138
|
if is_match: node = child; break
|
139
|
|
140
|
# Create node
|
141
|
if node == None:
|
142
|
if not create: return None
|
143
|
if elem.is_attr:
|
144
|
parent.setAttribute(elem.name, '')
|
145
|
node = parent.getAttributeNode(elem.name)
|
146
|
else: node = parent.appendChild(doc.createElement(elem.name))
|
147
|
if elem.value != None: xml_dom.set_value(doc, node, elem.value)
|
148
|
for attr in elem.attrs: get(doc, attr, create, last_only, node)
|
149
|
|
150
|
for branch in elem.other_branches:
|
151
|
branch = copy.deepcopy(branch)
|
152
|
set_value(branch, value(xpath))
|
153
|
get(doc, branch, create, last_only, node)
|
154
|
|
155
|
# Follow pointer
|
156
|
if elem.is_ptr:
|
157
|
xpath = copy.deepcopy(xpath[elem_idx+1:]) # rest of XPath
|
158
|
id_elem = backward_id(xpath[instance_level])
|
159
|
if id_elem != None:
|
160
|
# backward (child-to-parent) pointer with target ID attr
|
161
|
set_value(id_elem, xml_dom.get_id(node))
|
162
|
else: # forward (parent-to-child) pointer
|
163
|
id_ = xml_dom.value(node)
|
164
|
obj_xpath = obj(xpath) # target object
|
165
|
if id_ == None or get(doc, obj_xpath, False, True) == None:
|
166
|
# no target or target attrs don't match
|
167
|
if not create: return None
|
168
|
|
169
|
# Use last target object's ID + 1
|
170
|
obj_xpath[-1].attrs = [] # just get by tag name
|
171
|
last = get(doc, obj_xpath, False, True)
|
172
|
if last != None: id_ = str(int(xml_dom.get_id(last)) + 1)
|
173
|
else: id_ = '0'
|
174
|
|
175
|
# Will append if target attrs didn't match. Place ! in XPath
|
176
|
# after element to fork at to avoid this.
|
177
|
xml_dom.set_value(doc, node, id_)
|
178
|
else: last_only = False
|
179
|
set_id(xpath, id_)
|
180
|
return get(doc, xpath, create, last_only)
|
181
|
|
182
|
parent = node
|
183
|
return parent
|
184
|
|
185
|
def put_obj(doc, xpath, id_, has_types, value=None):
|
186
|
xpath = copy.deepcopy(xpath) # don't modify input!
|
187
|
set_id(xpath, id_, has_types)
|
188
|
if value != None: set_value(xpath, value)
|
189
|
get(doc, xpath, True)
|