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
    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 78 aaronmk
        self.other_branches = [] # temp implementation for split paths
18 21 aaronmk
19
    def __repr__(self):
20
        str_ = ''
21
        if self.is_attr: str_ += '@'
22 25 aaronmk
        str_ += self.name
23
        if self.attrs != []: str_ += repr(self.attrs)
24
        if self.value != None: str_ += '='+repr(self.value)
25 21 aaronmk
        if self.is_ptr: str_ += '->'
26
        return str_
27
28
    def __eq__(self, other): return self.__dict__ == other.__dict__
29
30 24 aaronmk
def value(path): return path[-1].value
31
32 22 aaronmk
def set_value(path, value): path[-1].value = value
33
34 32 aaronmk
def backward_id(elem):
35 59 aaronmk
    if len(elem.attrs) >= 1 and value(elem.attrs[0]) == None and\
36
    len(elem.attrs[0]) == 1: return elem.attrs[0]
37 32 aaronmk
    else: return None
38
39 76 aaronmk
def parse(str_):
40
    parser = Parser(str_)
41 21 aaronmk
42 76 aaronmk
    def _path():
43 21 aaronmk
        tree = []
44
        while True:
45 38 aaronmk
            # Split path
46 76 aaronmk
            if parser.str_('{'):
47 78 aaronmk
                paths = tree[-1].other_branches
48 38 aaronmk
                while True:
49 78 aaronmk
                    paths.append(_path())
50 76 aaronmk
                    if not parser.str_(','): break
51
                parser.str_('}', required=True)
52 78 aaronmk
                tree += paths.pop(0) # use first subpath for now
53 38 aaronmk
                break # nothing allowed after split path
54 36 aaronmk
55 76 aaronmk
            elem = XpathElem(is_attr=parser.str_('@'),
56
                name=parser.re(r'[\w.*]+', required=True))
57 38 aaronmk
58 36 aaronmk
            # Attrs
59 76 aaronmk
            if parser.str_('['):
60 36 aaronmk
                while True:
61 85 aaronmk
                    elem.attrs.append(_path())
62 76 aaronmk
                    if not parser.str_(','): break
63
                parser.str_(']', required=True)
64 36 aaronmk
65 76 aaronmk
            elem.is_ptr = parser.str_('->')
66 21 aaronmk
            tree.append(elem)
67 36 aaronmk
68
            # Lookahead assertion
69 76 aaronmk
            if parser.str_('('):
70
                parser.str_('/', required=True) # next / is inside ()
71
                path = _path()
72
                parser.str_(')', required=True)
73 36 aaronmk
                elem.attrs.append(path)
74
                tree += path
75
76 76 aaronmk
            if not parser.str_('/'): break
77 32 aaronmk
78 85 aaronmk
        if parser.str_('='): set_value(tree, parser.re(r'[\w.|]*'))
79
80 32 aaronmk
        # Expand * abbrs
81 70 aaronmk
        for i in reversed(xrange(len(tree))):
82
            elem = tree[i]
83 32 aaronmk
            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 70 aaronmk
                try: elem.name = before+tree[i+offset].name+after
90 32 aaronmk
                except IndexError: pass # no replacement elem
91
92 21 aaronmk
        return tree
93 76 aaronmk
94
    parser.str_('/') # optional leading /
95
    path = _path()
96
    parser.end()
97
    return path
98 21 aaronmk
99 26 aaronmk
instance_level = 1
100 22 aaronmk
101 26 aaronmk
def obj(path):
102 55 aaronmk
    obj_path = copy.deepcopy(path[:instance_level+1])
103 26 aaronmk
    obj_path[-1].is_ptr = False # prevent pointer w/o target
104
    return obj_path
105
106 22 aaronmk
def set_id(path, id_, has_types=True):
107 26 aaronmk
    if has_types: id_level = instance_level
108 21 aaronmk
    else: id_level = 0
109
    path[id_level].attrs.append([XpathElem('id', id_, is_attr=True)])
110 62 aaronmk
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 77 aaronmk
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 83 aaronmk
    for elem_idx, elem in enumerate(xpath):
121 77 aaronmk
        # 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 78 aaronmk
        for branch in elem.other_branches:
151 81 aaronmk
            branch = copy.deepcopy(branch)
152 78 aaronmk
            set_value(branch, value(xpath))
153
            get(doc, branch, create, last_only, node)
154
155 77 aaronmk
        # 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 82 aaronmk
185 85 aaronmk
def put_obj(doc, xpath, id_, has_types, value=None):
186 82 aaronmk
    xpath = copy.deepcopy(xpath) # don't modify input!
187
    set_id(xpath, id_, has_types)
188 85 aaronmk
    if value != None: set_value(xpath, value)
189 82 aaronmk
    get(doc, xpath, True)