Project

General

Profile

1 21 aaronmk
# XPath-based XML tree manipulation
2
3 22 aaronmk
from copy import deepcopy
4 21 aaronmk
from xml.dom import Node
5
6
from Parser import Parser
7
import xml_util
8
9
class XpathElem:
10
    def __init__(self, name, value=None, attrs=None, is_attr=False,
11
        is_ptr=False):
12
        if attrs == None: attrs = []
13
        self.name = name
14
        self.value = value
15
        self.attrs = attrs
16
        self.is_attr = is_attr
17
        self.is_ptr = is_ptr
18
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
    if len(elem.attrs) >= 1 and value(elem.attrs[0]) == None:
36
        return elem.attrs[0]
37
    else: return None
38
39 21 aaronmk
class XpathParser(Parser):
40
    def _main(self):
41
        self._match_str('/', required=True)
42
        return self._path()
43
44
    def _path(self):
45
        tree = []
46 25 aaronmk
        fork_idx = None
47
        elem_idx = 0
48 21 aaronmk
        while True:
49
            elem = XpathElem(is_attr=self._match_str('@'), name=self._fields())
50
            if self._match_str('['):
51
                elem.attrs = self._attrs()
52
                self._match_str(']', required=True)
53
            elem.is_ptr = self._match_str('->')
54 25 aaronmk
            if not elem.is_ptr and self._match_str('!'): fork_idx = elem_idx
55 21 aaronmk
            tree.append(elem)
56
            if not self._match_str('/'): break
57 25 aaronmk
            elem_idx += 1
58 32 aaronmk
59
        # Expand * abbrs
60
        elem_idx = 0
61
        for elem in tree:
62
            id_ = backward_id(elem)
63
            if id_ != None: elem = id_[0]; offset = -2
64
            elif elem.is_ptr: offset = 2
65
            else: offset = 1
66
            before, abbr, after = elem.name.partition('*')
67
            if abbr != '':
68
                try: elem.name = before+tree[elem_idx+offset].name+after
69
                except IndexError: pass # no replacement elem
70
            elem_idx += 1
71
72 25 aaronmk
        # Add lookahead assertion for rest of path
73
        if fork_idx != None: tree[fork_idx].attrs.append(tree[fork_idx+1:])
74 32 aaronmk
75 21 aaronmk
        return tree
76
77
    def _fields(self):
78
        if self._match_str('{'):
79
            tree = []
80
            while True:
81
                tree.append(self._field())
82
                if not self._match_str(','): break
83
            self._match_str('}', required=True)
84
            tree = tuple(tree)
85
            tree = tree[0] # just use first field for now
86
        else: tree = self._field()
87
        return tree
88
89
    def _attrs(self):
90
        tree = []
91
        while True:
92
            path = self._path()
93 22 aaronmk
            if self._match_str('='): set_value(path, self._value())
94 21 aaronmk
            tree.append(path)
95
            if not self._match_str(','): break
96
        return tree
97
98
    def _field(self):
99
        return self._name()
100
101 32 aaronmk
    def _name(self): return self._match_re(r'[\w.*]+', required=True)
102 21 aaronmk
103
    def _value(self): return self._match_re(r'[\w.|]+', required=True)
104
105 26 aaronmk
instance_level = 1
106 22 aaronmk
107 26 aaronmk
def obj(path):
108
    obj_path = deepcopy(path[:instance_level+1])
109
    obj_path[-1].is_ptr = False # prevent pointer w/o target
110
    return obj_path
111
112 22 aaronmk
def set_id(path, id_, has_types=True):
113 26 aaronmk
    if has_types: id_level = instance_level
114 21 aaronmk
    else: id_level = 0
115
    path[id_level].attrs.append([XpathElem('id', id_, is_attr=True)])
116
117 22 aaronmk
def get(doc, path, create=False, last_only=None, parent=None):
118 32 aaronmk
    # Warning: The last_only optimization may put data that should be together
119
    # into separate nodes
120 21 aaronmk
    if parent == None: parent = doc.documentElement
121 22 aaronmk
    if last_only == None: last_only = create
122
    elem_idx = 0
123 21 aaronmk
    for elem in path:
124 22 aaronmk
        # Find possible matches
125
        children = []
126
        if elem.is_attr:
127
            child = parent.getAttributeNode(elem.name)
128
            if child != None: children = [child]
129
        elif elem.name == '.': children = [parent]
130
        else: children = xml_util.by_tag_name(parent, elem.name, last_only)
131
132
        # Check each match
133 21 aaronmk
        node = None
134 22 aaronmk
        for child in children:
135
            is_match = elem.value == None or xml_util.value(child) == elem.value
136
            for attr in elem.attrs:
137
                if not is_match: break
138
                is_match = get(doc, attr, False, last_only, child) != None
139
            if is_match: node = child; break
140
141
        # Create node
142 21 aaronmk
        if node == None:
143
            if not create: return None
144
            if elem.is_attr:
145
                parent.setAttribute(elem.name, '')
146
                node = parent.getAttributeNode(elem.name)
147
            else: node = parent.appendChild(doc.createElement(elem.name))
148 22 aaronmk
            if elem.value != None: xml_util.set_value(doc, node, elem.value)
149
            for attr in elem.attrs: get(doc, attr, create, last_only, node)
150
151
        # Follow pointer
152 21 aaronmk
        if elem.is_ptr:
153 25 aaronmk
            path = deepcopy(path[elem_idx+1:]) # rest of path
154 32 aaronmk
            id_elem = backward_id(path[instance_level])
155
            if id_elem != None:
156 22 aaronmk
                # backward (child-to-parent) pointer with target ID attr
157 32 aaronmk
                set_value(id_elem, xml_util.get_id(node))
158 22 aaronmk
            else: # forward (parent-to-child) pointer
159
                id_ = xml_util.value(node)
160 26 aaronmk
                obj_path = obj(path) # target object
161 25 aaronmk
                if id_ == None or get(doc, obj_path, False, True) == None:
162
                    # no target or target attrs don't match
163 22 aaronmk
                    if not create: return None
164 25 aaronmk
165 22 aaronmk
                    # Use last target object's ID + 1
166 26 aaronmk
                    obj_path[-1].attrs = [] # just get by tag name
167
                    last = get(doc, obj_path, False, True)
168 25 aaronmk
                    if last != None: id_ = str(int(xml_util.get_id(last)) + 1)
169 22 aaronmk
                    else: id_ = '0'
170 25 aaronmk
171
                    # Will append if target attrs didn't match. Place ! in XPath
172
                    # after element to fork at to avoid this.
173 22 aaronmk
                    xml_util.set_value(doc, node, id_)
174 23 aaronmk
                else: last_only = False
175 25 aaronmk
                set_id(path, id_)
176
            return get(doc, path, create, last_only)
177 22 aaronmk
178 21 aaronmk
        parent = node
179 22 aaronmk
        elem_idx += 1
180 21 aaronmk
    return parent