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 36 aaronmk
        self._match_str('/') # optional leading /
42 21 aaronmk
        return self._path()
43
44
    def _path(self):
45
        tree = []
46 38 aaronmk
        trailing_slash = False
47 21 aaronmk
        while True:
48 38 aaronmk
            # 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 36 aaronmk
58 38 aaronmk
            elem = XpathElem(is_attr=self._match_str('@'),
59
                name=self._match_re(r'[\w.*]+', required=True))
60
61 36 aaronmk
            # Attrs
62 21 aaronmk
            if self._match_str('['):
63 36 aaronmk
                elem.attrs = []
64
                while True:
65
                    path = self._path()
66 38 aaronmk
                    if self._match_str('='):
67
                        set_value(path, self._match_re(r'[\w.|]*'))
68 36 aaronmk
                    elem.attrs.append(path)
69
                    if not self._match_str(','): break
70 21 aaronmk
                self._match_str(']', required=True)
71 36 aaronmk
72 21 aaronmk
            elem.is_ptr = self._match_str('->')
73
            tree.append(elem)
74 36 aaronmk
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 21 aaronmk
            if not self._match_str('/'): break
84 32 aaronmk
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 21 aaronmk
        return tree
99
100 26 aaronmk
instance_level = 1
101 22 aaronmk
102 26 aaronmk
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 22 aaronmk
def set_id(path, id_, has_types=True):
108 26 aaronmk
    if has_types: id_level = instance_level
109 21 aaronmk
    else: id_level = 0
110
    path[id_level].attrs.append([XpathElem('id', id_, is_attr=True)])
111
112 22 aaronmk
def get(doc, path, create=False, last_only=None, parent=None):
113 32 aaronmk
    # Warning: The last_only optimization may put data that should be together
114
    # into separate nodes
115 21 aaronmk
    if parent == None: parent = doc.documentElement
116 22 aaronmk
    if last_only == None: last_only = create
117
    elem_idx = 0
118 21 aaronmk
    for elem in path:
119 22 aaronmk
        # 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 21 aaronmk
        node = None
129 22 aaronmk
        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 21 aaronmk
        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 22 aaronmk
            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 21 aaronmk
        if elem.is_ptr:
148 25 aaronmk
            path = deepcopy(path[elem_idx+1:]) # rest of path
149 32 aaronmk
            id_elem = backward_id(path[instance_level])
150
            if id_elem != None:
151 22 aaronmk
                # backward (child-to-parent) pointer with target ID attr
152 32 aaronmk
                set_value(id_elem, xml_util.get_id(node))
153 22 aaronmk
            else: # forward (parent-to-child) pointer
154
                id_ = xml_util.value(node)
155 26 aaronmk
                obj_path = obj(path) # target object
156 25 aaronmk
                if id_ == None or get(doc, obj_path, False, True) == None:
157
                    # no target or target attrs don't match
158 22 aaronmk
                    if not create: return None
159 25 aaronmk
160 22 aaronmk
                    # Use last target object's ID + 1
161 26 aaronmk
                    obj_path[-1].attrs = [] # just get by tag name
162
                    last = get(doc, obj_path, False, True)
163 25 aaronmk
                    if last != None: id_ = str(int(xml_util.get_id(last)) + 1)
164 22 aaronmk
                    else: id_ = '0'
165 25 aaronmk
166
                    # Will append if target attrs didn't match. Place ! in XPath
167
                    # after element to fork at to avoid this.
168 22 aaronmk
                    xml_util.set_value(doc, node, id_)
169 23 aaronmk
                else: last_only = False
170 25 aaronmk
                set_id(path, id_)
171
            return get(doc, path, create, last_only)
172 22 aaronmk
173 21 aaronmk
        parent = node
174 22 aaronmk
        elem_idx += 1
175 21 aaronmk
    return parent