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 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
def get(doc, xpath, create=False, last_only=None, parent=None):
139
    # Warning: The last_only optimization may put data that should be together
140
    # into separate nodes
141
    if parent == None: parent = doc.documentElement
142
    if last_only == None: last_only = create
143 99 aaronmk
144
    if create and not is_positive(xpath): return None
145 83 aaronmk
    for elem_idx, elem in enumerate(xpath):
146 77 aaronmk
        # Find possible matches
147
        children = []
148
        if elem.is_attr:
149
            child = parent.getAttributeNode(elem.name)
150
            if child != None: children = [child]
151
        elif elem.name == '.': children = [parent]
152
        else:
153
            children = xml_dom.by_tag_name(parent, elem.name,
154 94 aaronmk
            last_only and (elem.keys == [] or is_instance(elem)))
155 77 aaronmk
156
        # Check each match
157
        node = None
158
        for child in children:
159
            is_match = elem.value == None or xml_dom.value(child) == elem.value
160 94 aaronmk
            for attr in elem.keys:
161 77 aaronmk
                if not is_match: break
162 97 aaronmk
                is_match = (get(doc, attr, False, last_only, child) != None)\
163 99 aaronmk
                == is_positive(attr)
164 77 aaronmk
            if is_match: node = child; break
165
166
        # Create node
167
        if node == None:
168
            if not create: return None
169
            if elem.is_attr:
170
                parent.setAttribute(elem.name, '')
171
                node = parent.getAttributeNode(elem.name)
172
            else: node = parent.appendChild(doc.createElement(elem.name))
173
            if elem.value != None: xml_dom.set_value(doc, node, elem.value)
174 95 aaronmk
        if create:
175 94 aaronmk
            for attr in elem.keys + elem.attrs:
176 99 aaronmk
                get(doc, attr, create, last_only, node)
177 77 aaronmk
178 78 aaronmk
        for branch in elem.other_branches:
179 81 aaronmk
            branch = copy.deepcopy(branch)
180 78 aaronmk
            set_value(branch, value(xpath))
181
            get(doc, branch, create, last_only, node)
182
183 77 aaronmk
        # Follow pointer
184
        if elem.is_ptr:
185
            xpath = copy.deepcopy(xpath[elem_idx+1:]) # rest of XPath
186
            id_elem = backward_id(xpath[instance_level])
187
            if id_elem != None:
188
                # backward (child-to-parent) pointer with target ID attr
189
                set_value(id_elem, xml_dom.get_id(node))
190
            else: # forward (parent-to-child) pointer
191
                id_ = xml_dom.value(node)
192
                obj_xpath = obj(xpath) # target object
193
                if id_ == None or get(doc, obj_xpath, False, True) == None:
194 94 aaronmk
                    # no target or target keys don't match
195 77 aaronmk
                    if not create: return None
196
197
                    # Use last target object's ID + 1
198 94 aaronmk
                    obj_xpath[-1].keys = [] # just get by tag name
199 77 aaronmk
                    last = get(doc, obj_xpath, False, True)
200
                    if last != None: id_ = str(int(xml_dom.get_id(last)) + 1)
201
                    else: id_ = '0'
202
203 94 aaronmk
                    # Will append if target keys didn't match. Place ! in XPath
204 77 aaronmk
                    # after element to fork at to avoid this.
205
                    xml_dom.set_value(doc, node, id_)
206
                else: last_only = False
207
                set_id(xpath, id_)
208
            return get(doc, xpath, create, last_only)
209
210
        parent = node
211
    return parent
212 82 aaronmk
213 85 aaronmk
def put_obj(doc, xpath, id_, has_types, value=None):
214 82 aaronmk
    xpath = copy.deepcopy(xpath) # don't modify input!
215
    set_id(xpath, id_, has_types)
216 85 aaronmk
    if value != None: set_value(xpath, value)
217 82 aaronmk
    get(doc, xpath, True)