Project

General

Profile

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