Project

General

Profile

1
# XPath-based XML tree manipulation
2

    
3
from copy import deepcopy
4
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
        str_ += self.name
23
        if self.attrs != []: str_ += repr(self.attrs)
24
        if self.value != None: str_ += '='+repr(self.value)
25
        if self.is_ptr: str_ += '->'
26
        return str_
27
    
28
    def __eq__(self, other): return self.__dict__ == other.__dict__
29

    
30
def value(path): return path[-1].value
31

    
32
def set_value(path, value): path[-1].value = value
33

    
34
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
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
        fork_idx = None
47
        elem_idx = 0
48
        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
            if not elem.is_ptr and self._match_str('!'): fork_idx = elem_idx
55
            tree.append(elem)
56
            if not self._match_str('/'): break
57
            elem_idx += 1
58
        
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
        # Add lookahead assertion for rest of path
73
        if fork_idx != None: tree[fork_idx].attrs.append(tree[fork_idx+1:])
74
        
75
        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
            if self._match_str('='): set_value(path, self._value())
94
            tree.append(path)
95
            if not self._match_str(','): break
96
        return tree
97
    
98
    def _field(self):
99
        return self._name()
100
    
101
    def _name(self): return self._match_re(r'[\w.*]+', required=True)
102
    
103
    def _value(self): return self._match_re(r'[\w.|]+', required=True)
104

    
105
instance_level = 1
106

    
107
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
def set_id(path, id_, has_types=True):
113
    if has_types: id_level = instance_level
114
    else: id_level = 0
115
    path[id_level].attrs.append([XpathElem('id', id_, is_attr=True)])
116

    
117
def get(doc, path, create=False, last_only=None, parent=None):
118
    # Warning: The last_only optimization may put data that should be together
119
    # into separate nodes
120
    if parent == None: parent = doc.documentElement
121
    if last_only == None: last_only = create
122
    elem_idx = 0
123
    for elem in path:
124
        # 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
        node = None
134
        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
        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
            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
        if elem.is_ptr:
153
            path = deepcopy(path[elem_idx+1:]) # rest of path
154
            id_elem = backward_id(path[instance_level])
155
            if id_elem != None:
156
                # backward (child-to-parent) pointer with target ID attr
157
                set_value(id_elem, xml_util.get_id(node))
158
            else: # forward (parent-to-child) pointer
159
                id_ = xml_util.value(node)
160
                obj_path = obj(path) # target object
161
                if id_ == None or get(doc, obj_path, False, True) == None:
162
                    # no target or target attrs don't match
163
                    if not create: return None
164
                    
165
                    # Use last target object's ID + 1
166
                    obj_path[-1].attrs = [] # just get by tag name
167
                    last = get(doc, obj_path, False, True)
168
                    if last != None: id_ = str(int(xml_util.get_id(last)) + 1)
169
                    else: id_ = '0'
170
                    
171
                    # Will append if target attrs didn't match. Place ! in XPath
172
                    # after element to fork at to avoid this.
173
                    xml_util.set_value(doc, node, id_)
174
                else: last_only = False
175
                set_id(path, id_)
176
            return get(doc, path, create, last_only)
177
        
178
        parent = node
179
        elem_idx += 1
180
    return parent
(10-10/10)