Package spade :: Package xmpp :: Module simplexml
[hide private]
[frames] | no frames]

Source Code for Module spade.xmpp.simplexml

  1  ##   simplexml.py based on Mattew Allum's xmlstream.py 
  2  ## 
  3  ##   Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov 
  4  ## 
  5  ##   This program is free software; you can redistribute it and/or modify 
  6  ##   it under the terms of the GNU General Public License as published by 
  7  ##   the Free Software Foundation; either version 2, or (at your option) 
  8  ##   any later version. 
  9  ## 
 10  ##   This program is distributed in the hope that it will be useful, 
 11  ##   but WITHOUT ANY WARRANTY; without even the implied warranty of 
 12  ##   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 13  ##   GNU General Public License for more details. 
 14   
 15  # $Id: simplexml.py,v 1.28 2005/08/06 04:44:54 snakeru Exp $ 
 16   
 17  """Simplexml module provides xmpppy library with all needed tools to handle XML nodes and XML streams. 
 18  I'm personally using it in many other separate projects. It is designed to be as standalone as possible.""" 
 19   
 20  import xml.parsers.expat 
 21   
22 -def XMLescape(txt):
23 """Returns provided string with symbols & < > " replaced by their respective XML entities.""" 24 return txt.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
25 26 ENCODING='utf-8'
27 -def ustr(what):
28 """Converts object "what" to unicode string using it's own __str__ method if accessible or unicode method otherwise.""" 29 if type(what) == type(u''): return what 30 try: r=what.__str__() 31 except AttributeError: r=str(what) 32 if type(r)<>type(u''): return unicode(r,ENCODING) 33 return r
34
35 -class Node:
36 """ Node class describes syntax of separate XML Node. It have a constructor that permits node creation 37 from set of "namespace name", attributes and payload of text strings and other nodes. 38 It does not natively support building node from text string and uses NodeBuilder class for that purpose. 39 After creation node can be mangled in many ways so it can be completely changed. 40 Also node can be serialised into string in one of two modes: default (where the textual representation 41 of node describes it exactly) and "fancy" - with whitespace added to make indentation and thus make 42 result more readable by human. 43 44 Node class have attribute FORCE_NODE_RECREATION that is defaults to False thus enabling fast node 45 replication from the some other node. The drawback of the fast way is that new node shares some 46 info with the "original" node that is changing the one node may influence the other. Though it is 47 rarely needed (in xmpppy it is never needed at all since I'm usually never using original node after 48 replication (and using replication only to move upwards on the classes tree). 49 """ 50 FORCE_NODE_RECREATION=0
51 - def __init__(self, tag=None, attrs={}, payload=[], parent=None, node=None):
52 """ Takes "tag" argument as the name of node (prepended by namespace, if needed and separated from it 53 by a space), attrs dictionary as the set of arguments, payload list as the set of textual strings 54 and child nodes that this node carries within itself and "parent" argument that is another node 55 that this one will be the child of. Also the __init__ can be provided with "node" argument that is 56 either a text string containing exactly one node or another Node instance to begin with. If both 57 "node" and other arguments is provided then the node initially created as replica of "node" 58 provided and then modified to be compliant with other arguments.""" 59 if node: 60 if self.FORCE_NODE_RECREATION and type(node)==type(self): node=str(node) 61 if type(node)<>type(self): node=NodeBuilder(node,self) 62 else: 63 self.name,self.namespace,self.attrs,self.data,self.kids,self.parent = node.name,node.namespace,{},[],[],node.parent 64 for key in node.attrs.keys(): self.attrs[key]=node.attrs[key] 65 for data in node.data: self.data.append(data) 66 for kid in node.kids: self.kids.append(kid) 67 else: self.name,self.namespace,self.attrs,self.data,self.kids,self.parent = 'tag','',{},[],[],None 68 69 if tag: self.namespace, self.name = ([self.namespace]+tag.split())[-2:] 70 if parent: self.parent = parent 71 if self.parent and not self.namespace: self.namespace=self.parent.namespace 72 for attr in attrs.keys(): 73 self.attrs[attr]=attrs[attr] 74 if type(payload) in (type(''),type(u'')): payload=[payload] 75 for i in payload: 76 if type(i)==type(self): self.addChild(node=i) 77 else: self.data.append(ustr(i))
78
79 - def __str__(self,fancy=0):
80 """ Method used to dump node into textual representation. 81 if "fancy" argument is set to True produces indented output for readability.""" 82 s = (fancy-1) * 2 * ' ' + "<" + self.name 83 if self.namespace: 84 if not self.parent or self.parent.namespace!=self.namespace: 85 s = s + ' xmlns="%s"'%self.namespace 86 for key in self.attrs.keys(): 87 val = ustr(self.attrs[key]) 88 s = s + ' %s="%s"' % ( key, XMLescape(val) ) 89 s = s + ">" 90 cnt = 0 91 if self.kids: 92 if fancy: s = s + "\n" 93 for a in self.kids: 94 if not fancy and (len(self.data)-1)>=cnt: s=s+XMLescape(self.data[cnt]) 95 elif (len(self.data)-1)>=cnt: s=s+XMLescape(self.data[cnt].strip()) 96 s = s + a.__str__(fancy and fancy+1) 97 cnt=cnt+1 98 if not fancy and (len(self.data)-1) >= cnt: s = s + XMLescape(self.data[cnt]) 99 elif (len(self.data)-1) >= cnt: s = s + XMLescape(self.data[cnt].strip()) 100 if not self.kids and s[-1:]=='>': 101 s=s[:-1]+' />' 102 if fancy: s = s + "\n" 103 else: 104 if fancy and not self.data: s = s + (fancy-1) * 2 * ' ' 105 s = s + "</" + self.name + ">" 106 if fancy: s = s + "\n" 107 return s
108 - def addChild(self, name=None, attrs={}, payload=[], namespace=None, node=None):
109 """ If "node" argument is provided, adds it as child node. Else creates new node from 110 the other arguments' values and adds it as well.""" 111 if namespace: name=namespace+' '+name 112 if node: 113 newnode=node 114 node.parent = self 115 else: newnode=Node(tag=name, parent=self, attrs=attrs, payload=payload) 116 self.kids.append(newnode) 117 return newnode
118 - def addData(self, data):
119 """ Adds some CDATA to node. """ 120 self.data.append(ustr(data))
121 - def clearData(self):
122 """ Removes all CDATA from the node. """ 123 self.data=[]
124 - def delAttr(self, key):
125 """ Deletes an attribute "key" """ 126 del self.attrs[key]
127 - def delChild(self, node, attrs={}):
128 """ Deletes the "node" from the node's childs list, if "node" is an instance. 129 Else deletes the first node that have specified name and (optionally) attributes. """ 130 if type(node)<>type(self): node=self.getTag(node,attrs) 131 self.kids.remove(node) 132 return node
133 - def getAttrs(self):
134 """ Returns all node's attributes as dictionary. """ 135 return self.attrs
136 - def getAttr(self, key):
137 """ Returns value of specified attribute. """ 138 try: return self.attrs[key] 139 except: return None
140 - def getChildren(self):
141 """ Returns all node's child nodes as list. """ 142 return self.kids
143 - def getData(self):
144 """ Returns all node CDATA as string (concatenated). """ 145 return ''.join(self.data)
146 - def getName(self):
147 """ Returns the name of node """ 148 return self.name
149 - def getNamespace(self):
150 """ Returns the namespace of node """ 151 return self.namespace
152 - def getParent(self):
153 """ Returns the parent of node (if present). """ 154 return self.parent
155 - def getPayload(self):
156 """ Return the payload of node i.e. list of child nodes and CDATA entries. 157 F.e. for "<node>text1<nodea/><nodeb/> text2</node>" will be returned list: 158 ['text1', <nodea instance>, <nodeb instance>, ' text2']. """ 159 ret=[] 160 for i in range(len(self.kids)+len(self.data)+1): 161 try: 162 if self.data[i]: ret.append(self.data[i]) 163 except IndexError: pass 164 try: ret.append(self.kids[i]) 165 except IndexError: pass 166 return ret
167 - def getTag(self, name, attrs={}, namespace=None):
168 """ Filters all child nodes using specified arguments as filter. 169 Returns the first found or None if not found. """ 170 return self.getTags(name, attrs, namespace, one=1)
171 - def getTagAttr(self,tag,attr):
172 """ Returns attribute value of the child with specified name (or None if no such attribute).""" 173 try: return self.getTag(tag).attrs[attr] 174 except: return None
175 - def getTagData(self,tag):
176 """ Returns cocatenated CDATA of the child with specified name.""" 177 try: return self.getTag(tag).getData() 178 except: return None
179 - def getTags(self, name, attrs={}, namespace=None, one=0):
180 """ Filters all child nodes using specified arguments as filter. 181 Returns the list of nodes found. """ 182 nodes=[] 183 for node in self.kids: 184 if namespace and namespace<>node.getNamespace(): continue 185 if node.getName() == name: 186 for key in attrs.keys(): 187 if not node.attrs.has_key(key) or node.attrs[key]<>attrs[key]: break 188 else: nodes.append(node) 189 if one and nodes: return nodes[0] 190 if not one: return nodes
191 - def setAttr(self, key, val):
192 """ Sets attribute "key" with the value "val". """ 193 self.attrs[key]=val
194 - def setData(self, data):
195 """ Sets node's CDATA to provided string. Resets all previous CDATA!""" 196 self.data=[ustr(data)]
197 - def setName(self,val):
198 """ Changes the node name. """ 199 self.name = val
200 - def setNamespace(self, namespace):
201 """ Changes the node namespace. """ 202 self.namespace=namespace
203 - def setParent(self, node):
204 """ Sets node's parent to "node". WARNING: do not checks if the parent already present 205 and not removes the node from the list of childs of previous parent. """ 206 self.parent = node
207 - def setPayload(self,payload,add=0):
208 """ Sets node payload according to the list specified. WARNING: completely replaces all node's 209 previous content. If you wish just to add child or CDATA - use addData or addChild methods. """ 210 if type(payload) in (type(''),type(u'')): payload=[payload] 211 if add: self.kids+=payload 212 else: self.kids=payload
213 - def setTag(self, name, attrs={}, namespace=None):
214 """ Same as getTag but if the node with specified namespace/attributes not found, creates such 215 node and returns it. """ 216 node=self.getTags(name, attrs, namespace=namespace, one=1) 217 if node: return node 218 else: return self.addChild(name, attrs, namespace=namespace)
219 - def setTagAttr(self,tag,attr,val):
220 """ Creates new node (if not already present) with name "tag" 221 and sets it's attribute "attr" to value "val". """ 222 try: self.getTag(tag).attrs[attr]=val 223 except: self.addChild(tag,attrs={attr:val})
224 - def setTagData(self,tag,val,attrs={}):
225 """ Creates new node (if not already present) with name "tag" and (optionally) attributes "attrs" 226 and sets it's CDATA to string "val". """ 227 try: self.getTag(tag,attrs).setData(ustr(val)) 228 except: self.addChild(tag,attrs,payload=[ustr(val)])
229 - def has_attr(self,key):
230 """ Checks if node have attribute "key".""" 231 return self.attrs.has_key(key)
232 - def __getitem__(self,item):
233 """ Returns node's attribute "item" value. """ 234 return self.getAttr(item)
235 - def __setitem__(self,item,val):
236 """ Sets node's attribute "item" value. """ 237 return self.setAttr(item,val)
238 - def __delitem__(self,item):
239 """ Deletes node's attribute "item". """ 240 return self.delAttr(item,val)
241 - def __getattr__(self,attr):
242 """ Reduce memory usage caused by T/NT classes - use memory only when needed. """ 243 if attr=='T': 244 self.T=T(self) 245 return self.T 246 if attr=='NT': 247 self.NT=NT(self) 248 return self.NT 249 raise AttributeError
250
251 -class T:
252 """ Auxiliary class used to quick access to node's child nodes. """
253 - def __init__(self,node): self.__dict__['node']=node
254 - def __getattr__(self,attr): return self.node.getTag(attr)
255 - def __setattr__(self,attr,val):
256 if isinstance(val,Node): Node.__init__(self.node.setTag(attr),node=val) 257 else: return self.node.setTagData(attr,val)
258 - def __delattr__(self,attr): return self.node.delChild(attr)
259
260 -class NT(T):
261 """ Auxiliary class used to quick create node's child nodes. """
262 - def __getattr__(self,attr): return self.node.addChild(attr)
263 - def __setattr__(self,attr,val):
264 if isinstance(val,Node): self.node.addChild(attr,node=val) 265 else: return self.node.addChild(attr,payload=[val])
266 267 DBG_NODEBUILDER = 'nodebuilder'
268 -class NodeBuilder:
269 """ Builds a Node class minidom from data parsed to it. This class used for two purposes: 270 1. Creation an XML Node from a textual representation. F.e. reading a config file. See an XML2Node method. 271 2. Handling an incoming XML stream. This is done by mangling 272 the __dispatch_depth parameter and redefining the dispatch method. 273 You do not need to use this class directly if you do not designing your own XML handler."""
274 - def __init__(self,data=None,initial_node=None):
275 """ Takes two optional parameters: "data" and "initial_node". 276 By default class initialised with empty Node class instance. 277 Though, if "initial_node" is provided it used as "starting point". 278 You can think about it as of "node upgrade". 279 "data" (if provided) feeded to parser immidiatedly after instance init. 280 """ 281 self.DEBUG(DBG_NODEBUILDER, "Preparing to handle incoming XML stream.", 'start') 282 self._parser = xml.parsers.expat.ParserCreate(namespace_separator=' ') 283 self._parser.StartElementHandler = self.starttag 284 self._parser.EndElementHandler = self.endtag 285 self._parser.CharacterDataHandler = self.handle_data 286 self._parser.StartNamespaceDeclHandler = self.handle_namespace_start 287 self.Parse = self._parser.Parse 288 289 self.__depth = 0 290 self._dispatch_depth = 1 291 self._document_attrs = None 292 self._mini_dom=initial_node 293 self.last_is_data = 1 294 self._ptr=None 295 self.namespaces={"http://www.w3.org/XML/1998/namespace":'xml:'} 296 self.xmlns="http://www.w3.org/XML/1998/namespace" 297 298 if data: self._parser.Parse(data,1)
299
300 - def destroy(self):
301 """ Method used to allow class instance to be garbage-collected. """ 302 self._parser.StartElementHandler = None 303 self._parser.EndElementHandler = None 304 self._parser.CharacterDataHandler = None 305 self._parser.StartNamespaceDeclHandler = None
306
307 - def starttag(self, tag, attrs):
308 """XML Parser callback. Used internally""" 309 attlist=attrs.keys() # 310 for attr in attlist: # FIXME: Crude hack. And it also slows down the whole library considerably. 311 sp=attr.rfind(" ") # 312 if sp==-1: continue # 313 ns=attr[:sp] # 314 attrs[self.namespaces[ns]+attr[sp+1:]]=attrs[attr] 315 del attrs[attr] # 316 self.__depth += 1 317 self.DEBUG(DBG_NODEBUILDER, "DEPTH -> %i , tag -> %s, attrs -> %s" % (self.__depth, tag, `attrs`), 'down') 318 if self.__depth == self._dispatch_depth: 319 if not self._mini_dom : self._mini_dom = Node(tag=tag, attrs=attrs) 320 else: Node.__init__(self._mini_dom,tag=tag, attrs=attrs) 321 self._ptr = self._mini_dom 322 elif self.__depth > self._dispatch_depth: 323 self._ptr.kids.append(Node(tag=tag,parent=self._ptr,attrs=attrs)) 324 self._ptr = self._ptr.kids[-1] 325 if self.__depth == 1: 326 self._document_attrs = attrs 327 ns, name = (['']+tag.split())[-2:] 328 self.stream_header_received(ns, name, attrs) 329 if not self.last_is_data and self._ptr.parent: self._ptr.parent.data.append('') 330 self.last_is_data = 0
331
332 - def endtag(self, tag ):
333 """XML Parser callback. Used internally""" 334 self.DEBUG(DBG_NODEBUILDER, "DEPTH -> %i , tag -> %s" % (self.__depth, tag), 'up') 335 if self.__depth == self._dispatch_depth: 336 self.dispatch(self._mini_dom) 337 elif self.__depth > self._dispatch_depth: 338 self._ptr = self._ptr.parent 339 else: 340 self.DEBUG(DBG_NODEBUILDER, "Got higher than dispatch level. Stream terminated?", 'stop') 341 self.__depth -= 1 342 self.last_is_data = 0 343 if self.__depth == 0: self.stream_footer_received()
344
345 - def handle_data(self, data):
346 """XML Parser callback. Used internally""" 347 self.DEBUG(DBG_NODEBUILDER, data, 'data') 348 if not self._ptr: return 349 if self.last_is_data: 350 self._ptr.data[-1] += data 351 else: 352 self._ptr.data.append(data) 353 self.last_is_data = 1
354
355 - def handle_namespace_start(self, prefix, uri):
356 """XML Parser callback. Used internally""" 357 if prefix: self.namespaces[uri]=prefix+':' 358 else: self.xmlns=uri
359 - def DEBUG(self, level, text, comment=None):
360 """ Gets all NodeBuilder walking events. Can be used for debugging if redefined."""
361 - def getDom(self):
362 """ Returns just built Node. """ 363 return self._mini_dom
364 - def dispatch(self,stanza):
365 """ Gets called when the NodeBuilder reaches some level of depth on it's way up with the built 366 node as argument. Can be redefined to convert incoming XML stanzas to program events. """
367 - def stream_header_received(self,ns,tag,attrs):
368 """ Method called when stream just opened. """
371
372 -def XML2Node(xml):
373 """ Converts supplied textual string into XML node. Handy f.e. for reading configuration file. 374 Raises xml.parser.expat.parsererror if provided string is not well-formed XML. """ 375 return NodeBuilder(xml).getDom()
376
377 -def BadXML2Node(xml):
378 """ Converts supplied textual string into XML node. Survives if xml data is cutted half way round. 379 I.e. "<html>some text <br>some more text". Will raise xml.parser.expat.parsererror on misplaced 380 tags though. F.e. "<b>some text <br>some more text</b>" will not work.""" 381 return NodeBuilder(xml).getDom()
382