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('/') # optional leading /
42
        return self._path()
43
    
44
    def _path(self):
45
        tree = []
46
        trailing_slash = False
47
        while True:
48
            # Split path
49
            if self._match_str('{'):
50
                paths = []
51
                while True:
52
                    paths.append(tree + self._path())
53
                    if not self._match_str(','): break
54
                self._match_str('}', required=True)
55
                tree = paths[0] # just use first subpath for now
56
                break # nothing allowed after split path
57
            
58
            elem = XpathElem(is_attr=self._match_str('@'),
59
                name=self._match_re(r'[\w.*]+', required=True))
60
            
61
            # Attrs
62
            if self._match_str('['):
63
                elem.attrs = []
64
                while True:
65
                    path = self._path()
66
                    if self._match_str('='):
67
                        set_value(path, self._match_re(r'[\w.|]*'))
68
                    elem.attrs.append(path)
69
                    if not self._match_str(','): break
70
                self._match_str(']', required=True)
71
            
72
            elem.is_ptr = self._match_str('->')
73
            tree.append(elem)
74
            
75
            # Lookahead assertion
76
            if self._match_str('('):
77
                self._match_str('/', required=True) # next / is inside ()
78
                path = self._path()
79
                self._match_str(')', required=True)
80
                elem.attrs.append(path)
81
                tree += path
82
            
83
            if not self._match_str('/'): break
84
        
85
        # Expand * abbrs
86
        elem_idx = 0
87
        for elem in tree:
88
            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
                try: elem.name = before+tree[elem_idx+offset].name+after
95
                except IndexError: pass # no replacement elem
96
            elem_idx += 1
97
        
98
        return tree
99

    
100
instance_level = 1
101

    
102
def obj(path):
103
    obj_path = deepcopy(path[:instance_level+1])
104
    obj_path[-1].is_ptr = False # prevent pointer w/o target
105
    return obj_path
106

    
107
def set_id(path, id_, has_types=True):
108
    if has_types: id_level = instance_level
109
    else: id_level = 0
110
    path[id_level].attrs.append([XpathElem('id', id_, is_attr=True)])
111

    
112
def get(doc, path, create=False, last_only=None, parent=None):
113
    # Warning: The last_only optimization may put data that should be together
114
    # into separate nodes
115
    if parent == None: parent = doc.documentElement
116
    if last_only == None: last_only = create
117
    elem_idx = 0
118
    for elem in path:
119
        # Find possible matches
120
        children = []
121
        if elem.is_attr:
122
            child = parent.getAttributeNode(elem.name)
123
            if child != None: children = [child]
124
        elif elem.name == '.': children = [parent]
125
        else: children = xml_util.by_tag_name(parent, elem.name, last_only)
126
        
127
        # Check each match
128
        node = None
129
        for child in children:
130
            is_match = elem.value == None or xml_util.value(child) == elem.value
131
            for attr in elem.attrs:
132
                if not is_match: break
133
                is_match = get(doc, attr, False, last_only, child) != None
134
            if is_match: node = child; break
135
        
136
        # Create node
137
        if node == None:
138
            if not create: return None
139
            if elem.is_attr:
140
                parent.setAttribute(elem.name, '')
141
                node = parent.getAttributeNode(elem.name)
142
            else: node = parent.appendChild(doc.createElement(elem.name))
143
            if elem.value != None: xml_util.set_value(doc, node, elem.value)
144
            for attr in elem.attrs: get(doc, attr, create, last_only, node)
145
        
146
        # Follow pointer
147
        if elem.is_ptr:
148
            path = deepcopy(path[elem_idx+1:]) # rest of path
149
            id_elem = backward_id(path[instance_level])
150
            if id_elem != None:
151
                # backward (child-to-parent) pointer with target ID attr
152
                set_value(id_elem, xml_util.get_id(node))
153
            else: # forward (parent-to-child) pointer
154
                id_ = xml_util.value(node)
155
                obj_path = obj(path) # target object
156
                if id_ == None or get(doc, obj_path, False, True) == None:
157
                    # no target or target attrs don't match
158
                    if not create: return None
159
                    
160
                    # Use last target object's ID + 1
161
                    obj_path[-1].attrs = [] # just get by tag name
162
                    last = get(doc, obj_path, False, True)
163
                    if last != None: id_ = str(int(xml_util.get_id(last)) + 1)
164
                    else: id_ = '0'
165
                    
166
                    # Will append if target attrs didn't match. Place ! in XPath
167
                    # after element to fork at to avoid this.
168
                    xml_util.set_value(doc, node, id_)
169
                else: last_only = False
170
                set_id(path, id_)
171
            return get(doc, path, create, last_only)
172
        
173
        parent = node
174
        elem_idx += 1
175
    return parent
(10-10/10)