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