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