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