simplexml.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. # $Id$
  15. """Simplexml module provides xmpppy library with all needed tools to handle XML nodes and XML streams.
  16. I'm personally using it in many other separate projects. It is designed to be as standalone as possible."""
  17. import xml.parsers.expat
  18. def XMLescape(txt):
  19. """Returns provided string with symbols & < > " replaced by their respective XML entities."""
  20. # replace also FORM FEED and ESC, because they are not valid XML chars
  21. return txt.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;").replace('\x0C', "").replace('\x1B', "")
  22. ENCODING='utf-8'
  23. def ustr(what):
  24. """Converts object "what" to unicode string using it's own __str__ method if accessible or unicode method otherwise."""
  25. if isinstance(what, str): return what
  26. try: r=what.__str__()
  27. except AttributeError: r=str(what)
  28. if not isinstance(r, str): return str(r,ENCODING)
  29. return r
  30. class Node(object):
  31. """ Node class describes syntax of separate XML Node. It have a constructor that permits node creation
  32. from set of "namespace name", attributes and payload of text strings and other nodes.
  33. It does not natively support building node from text string and uses NodeBuilder class for that purpose.
  34. After creation node can be mangled in many ways so it can be completely changed.
  35. Also node can be serialised into string in one of two modes: default (where the textual representation
  36. of node describes it exactly) and "fancy" - with whitespace added to make indentation and thus make
  37. result more readable by human.
  38. Node class have attribute FORCE_NODE_RECREATION that is defaults to False thus enabling fast node
  39. replication from the some other node. The drawback of the fast way is that new node shares some
  40. info with the "original" node that is changing the one node may influence the other. Though it is
  41. rarely needed (in xmpppy it is never needed at all since I'm usually never using original node after
  42. replication (and using replication only to move upwards on the classes tree).
  43. """
  44. FORCE_NODE_RECREATION=0
  45. def __init__(self, tag=None, attrs={}, payload=[], parent=None, nsp=None, node_built=False, node=None):
  46. """ Takes "tag" argument as the name of node (prepended by namespace, if needed and separated from it
  47. by a space), attrs dictionary as the set of arguments, payload list as the set of textual strings
  48. and child nodes that this node carries within itself and "parent" argument that is another node
  49. that this one will be the child of. Also the __init__ can be provided with "node" argument that is
  50. either a text string containing exactly one node or another Node instance to begin with. If both
  51. "node" and other arguments is provided then the node initially created as replica of "node"
  52. provided and then modified to be compliant with other arguments."""
  53. if node:
  54. if self.FORCE_NODE_RECREATION and isinstance(node, Node):
  55. node=str(node)
  56. if not isinstance(node, Node):
  57. node=NodeBuilder(node,self)
  58. node_built = True
  59. else:
  60. self.name,self.namespace,self.attrs,self.data,self.kids,self.parent,self.nsd = node.name,node.namespace,{},[],[],node.parent,{}
  61. for key in list(node.attrs.keys()): self.attrs[key]=node.attrs[key]
  62. for data in node.data: self.data.append(data)
  63. for kid in node.kids: self.kids.append(kid)
  64. for k,v in list(node.nsd.items()): self.nsd[k] = v
  65. else: self.name,self.namespace,self.attrs,self.data,self.kids,self.parent,self.nsd = 'tag','',{},[],[],None,{}
  66. if parent:
  67. self.parent = parent
  68. self.nsp_cache = {}
  69. if nsp:
  70. for k,v in list(nsp.items()): self.nsp_cache[k] = v
  71. for attr,val in list(attrs.items()):
  72. if attr == 'xmlns':
  73. self.nsd[''] = val
  74. elif attr.startswith('xmlns:'):
  75. self.nsd[attr[6:]] = val
  76. self.attrs[attr]=attrs[attr]
  77. if tag:
  78. if node_built:
  79. pfx,self.name = (['']+tag.split(':'))[-2:]
  80. self.namespace = self.lookup_nsp(pfx)
  81. else:
  82. if ' ' in tag:
  83. self.namespace,self.name = tag.split()
  84. else:
  85. self.name = tag
  86. if isinstance(payload, str): payload=[payload]
  87. for i in payload:
  88. if isinstance(i, Node): self.addChild(node=i)
  89. else: self.data.append(ustr(i))
  90. def lookup_nsp(self,pfx=''):
  91. ns = self.nsd.get(pfx,None)
  92. if ns is None:
  93. ns = self.nsp_cache.get(pfx,None)
  94. if ns is None:
  95. if self.parent:
  96. ns = self.parent.lookup_nsp(pfx)
  97. self.nsp_cache[pfx] = ns
  98. else:
  99. return 'http://www.gajim.org/xmlns/undeclared'
  100. return ns
  101. def __str__(self,fancy=0):
  102. """ Method used to dump node into textual representation.
  103. if "fancy" argument is set to True produces indented output for readability."""
  104. s = (fancy-1) * 2 * ' ' + "<" + self.name
  105. if self.namespace:
  106. if not self.parent or self.parent.namespace!=self.namespace:
  107. if 'xmlns' not in self.attrs:
  108. s = s + ' xmlns="%s"'%self.namespace
  109. for key in list(self.attrs.keys()):
  110. val = ustr(self.attrs[key])
  111. s = s + ' %s="%s"' % ( key, XMLescape(val) )
  112. s = s + ">"
  113. cnt = 0
  114. if self.kids:
  115. if fancy: s = s + "\n"
  116. for a in self.kids:
  117. if not fancy and (len(self.data)-1)>=cnt: s=s+XMLescape(self.data[cnt])
  118. elif (len(self.data)-1)>=cnt: s=s+XMLescape(self.data[cnt].strip())
  119. if isinstance(a, Node):
  120. s = s + a.__str__(fancy and fancy+1)
  121. elif a:
  122. s = s + a.__str__()
  123. cnt=cnt+1
  124. if not fancy and (len(self.data)-1) >= cnt: s = s + XMLescape(self.data[cnt])
  125. elif (len(self.data)-1) >= cnt: s = s + XMLescape(self.data[cnt].strip())
  126. if not self.kids and s.endswith('>'):
  127. s=s[:-1]+' />'
  128. if fancy: s = s + "\n"
  129. else:
  130. if fancy and not self.data: s = s + (fancy-1) * 2 * ' '
  131. s = s + "</" + self.name + ">"
  132. if fancy: s = s + "\n"
  133. return s
  134. def getCDATA(self):
  135. """ Serialise node, dropping all tags and leaving CDATA intact.
  136. That is effectively kills all formatiing, leaving only text were contained in XML.
  137. """
  138. s = ""
  139. cnt = 0
  140. if self.kids:
  141. for a in self.kids:
  142. s=s+self.data[cnt]
  143. if a: s = s + a.getCDATA()
  144. cnt=cnt+1
  145. if (len(self.data)-1) >= cnt: s = s + self.data[cnt]
  146. return s
  147. def addChild(self, name=None, attrs={}, payload=[], namespace=None, node=None):
  148. """ If "node" argument is provided, adds it as child node. Else creates new node from
  149. the other arguments' values and adds it as well."""
  150. if 'xmlns' in attrs:
  151. raise AttributeError("Use namespace=x instead of attrs={'xmlns':x}")
  152. if node:
  153. newnode=node
  154. node.parent = self
  155. else: newnode=Node(tag=name, parent=self, attrs=attrs, payload=payload)
  156. if namespace:
  157. newnode.setNamespace(namespace)
  158. self.kids.append(newnode)
  159. self.data.append('')
  160. return newnode
  161. def addData(self, data):
  162. """ Adds some CDATA to node. """
  163. self.data.append(ustr(data))
  164. self.kids.append(None)
  165. def clearData(self):
  166. """ Removes all CDATA from the node. """
  167. self.data=[]
  168. def delAttr(self, key):
  169. """ Deletes an attribute "key" """
  170. del self.attrs[key]
  171. def delChild(self, node, attrs={}):
  172. """ Deletes the "node" from the node's childs list, if "node" is an instance.
  173. Else deletes the first node that have specified name and (optionally) attributes. """
  174. if not isinstance(node, Node): node=self.getTag(node,attrs)
  175. self.kids[self.kids.index(node)]=None
  176. return node
  177. def getAttrs(self):
  178. """ Returns all node's attributes as dictionary. """
  179. return self.attrs
  180. def getAttr(self, key):
  181. """ Returns value of specified attribute. """
  182. try: return self.attrs[key]
  183. except: return None
  184. def getChildren(self):
  185. """ Returns all node's child nodes as list. """
  186. return self.kids
  187. def getData(self):
  188. """ Returns all node CDATA as string (concatenated). """
  189. return ''.join(self.data)
  190. def getName(self):
  191. """ Returns the name of node """
  192. return self.name
  193. def getNamespace(self):
  194. """ Returns the namespace of node """
  195. return self.namespace
  196. def getParent(self):
  197. """ Returns the parent of node (if present). """
  198. return self.parent
  199. def getPayload(self):
  200. """ Return the payload of node i.e. list of child nodes and CDATA entries.
  201. F.e. for "<node>text1<nodea/><nodeb/> text2</node>" will be returned list:
  202. ['text1', <nodea instance>, <nodeb instance>, ' text2']. """
  203. ret=[]
  204. for i in range(max(len(self.data),len(self.kids))):
  205. if i < len(self.data) and self.data[i]: ret.append(self.data[i])
  206. if i < len(self.kids) and self.kids[i]: ret.append(self.kids[i])
  207. return ret
  208. def getTag(self, name, attrs={}, namespace=None):
  209. """ Filters all child nodes using specified arguments as filter.
  210. Returns the first found or None if not found. """
  211. return self.getTags(name, attrs, namespace, one=1)
  212. def getTagAttr(self,tag,attr):
  213. """ Returns attribute value of the child with specified name (or None if no such attribute)."""
  214. try: return self.getTag(tag).attrs[attr]
  215. except: return None
  216. def getTagData(self,tag):
  217. """ Returns cocatenated CDATA of the child with specified name."""
  218. try: return self.getTag(tag).getData()
  219. except: return None
  220. def getTags(self, name, attrs={}, namespace=None, one=0):
  221. """ Filters all child nodes using specified arguments as filter.
  222. Returns the list of nodes found. """
  223. nodes=[]
  224. for node in self.kids:
  225. if not node: continue
  226. if namespace and namespace!=node.getNamespace(): continue
  227. if node.getName() == name:
  228. for key in list(attrs.keys()):
  229. if key not in node.attrs or node.attrs[key]!=attrs[key]: break
  230. else: nodes.append(node)
  231. if one and nodes: return nodes[0]
  232. if not one: return nodes
  233. def iterTags(self, name, attrs={}, namespace=None):
  234. """ Iterate over all children using specified arguments as filter. """
  235. for node in self.kids:
  236. if not node: continue
  237. if namespace is not None and namespace!=node.getNamespace(): continue
  238. if node.getName() == name:
  239. for key in list(attrs.keys()):
  240. if key not in node.attrs or \
  241. node.attrs[key]!=attrs[key]: break
  242. else:
  243. yield node
  244. def setAttr(self, key, val):
  245. """ Sets attribute "key" with the value "val". """
  246. self.attrs[key]=val
  247. def setData(self, data):
  248. """ Sets node's CDATA to provided string. Resets all previous CDATA!"""
  249. self.data=[ustr(data)]
  250. def setName(self,val):
  251. """ Changes the node name. """
  252. self.name = val
  253. def setNamespace(self, namespace):
  254. """ Changes the node namespace. """
  255. self.namespace=namespace
  256. def setParent(self, node):
  257. """ Sets node's parent to "node". WARNING: do not checks if the parent already present
  258. and not removes the node from the list of childs of previous parent. """
  259. self.parent = node
  260. def setPayload(self,payload,add=0):
  261. """ Sets node payload according to the list specified. WARNING: completely replaces all node's
  262. previous content. If you wish just to add child or CDATA - use addData or addChild methods. """
  263. if isinstance(payload, str): payload=[payload]
  264. if add: self.kids+=payload
  265. else: self.kids=payload
  266. def setTag(self, name, attrs={}, namespace=None):
  267. """ Same as getTag but if the node with specified namespace/attributes not found, creates such
  268. node and returns it. """
  269. node=self.getTags(name, attrs, namespace=namespace, one=1)
  270. if node: return node
  271. else: return self.addChild(name, attrs, namespace=namespace)
  272. def setTagAttr(self,tag,attr,val):
  273. """ Creates new node (if not already present) with name "tag"
  274. and sets it's attribute "attr" to value "val". """
  275. try: self.getTag(tag).attrs[attr]=val
  276. except: self.addChild(tag,attrs={attr:val})
  277. def setTagData(self,tag,val,attrs={}):
  278. """ Creates new node (if not already present) with name "tag" and (optionally) attributes "attrs"
  279. and sets it's CDATA to string "val". """
  280. try: self.getTag(tag,attrs).setData(ustr(val))
  281. except: self.addChild(tag,attrs,payload=[ustr(val)])
  282. def has_attr(self,key):
  283. """ Checks if node have attribute "key"."""
  284. return key in self.attrs
  285. def __getitem__(self,item):
  286. """ Returns node's attribute "item" value. """
  287. return self.getAttr(item)
  288. def __setitem__(self,item,val):
  289. """ Sets node's attribute "item" value. """
  290. return self.setAttr(item,val)
  291. def __delitem__(self,item):
  292. """ Deletes node's attribute "item". """
  293. return self.delAttr(item)
  294. def __getattr__(self,attr):
  295. """ Reduce memory usage caused by T/NT classes - use memory only when needed. """
  296. if attr=='T':
  297. self.T=T(self)
  298. return self.T
  299. if attr=='NT':
  300. self.NT=NT(self)
  301. return self.NT
  302. raise AttributeError
  303. class T:
  304. """ Auxiliary class used to quick access to node's child nodes. """
  305. def __init__(self,node): self.__dict__['node']=node
  306. def __getattr__(self,attr): return self.node.getTag(attr)
  307. def __setattr__(self,attr,val):
  308. if isinstance(val,Node): Node.__init__(self.node.setTag(attr),node=val)
  309. else: return self.node.setTagData(attr,val)
  310. def __delattr__(self,attr): return self.node.delChild(attr)
  311. class NT(T):
  312. """ Auxiliary class used to quick create node's child nodes. """
  313. def __getattr__(self,attr): return self.node.addChild(attr)
  314. def __setattr__(self,attr,val):
  315. if isinstance(val,Node): self.node.addChild(attr,node=val)
  316. else: return self.node.addChild(attr,payload=[val])
  317. DBG_NODEBUILDER = 'nodebuilder'
  318. class NodeBuilder:
  319. """ Builds a Node class minidom from data parsed to it. This class used for two purposes:
  320. 1. Creation an XML Node from a textual representation. F.e. reading a config file. See an XML2Node method.
  321. 2. Handling an incoming XML stream. This is done by mangling
  322. the __dispatch_depth parameter and redefining the dispatch method.
  323. You do not need to use this class directly if you do not designing your own XML handler."""
  324. def __init__(self,data=None,initial_node=None):
  325. """ Takes two optional parameters: "data" and "initial_node".
  326. By default class initialised with empty Node class instance.
  327. Though, if "initial_node" is provided it used as "starting point".
  328. You can think about it as of "node upgrade".
  329. "data" (if provided) feeded to parser immidiatedly after instance init.
  330. """
  331. self.DEBUG(DBG_NODEBUILDER, "Preparing to handle incoming XML stream.", 'start')
  332. self._parser = xml.parsers.expat.ParserCreate()
  333. self._parser.StartElementHandler = self.starttag
  334. self._parser.EndElementHandler = self.endtag
  335. self._parser.CharacterDataHandler = self.handle_cdata
  336. self._parser.StartNamespaceDeclHandler = self.handle_namespace_start
  337. self._parser.buffer_text = True
  338. self.Parse = self._parser.Parse
  339. self.__depth = 0
  340. self.__last_depth = 0
  341. self.__max_depth = 0
  342. self._dispatch_depth = 1
  343. self._document_attrs = None
  344. self._document_nsp = None
  345. self._mini_dom=initial_node
  346. self.last_is_data = 1
  347. self._ptr=None
  348. self.data_buffer = None
  349. self.streamError = ''
  350. if data:
  351. self._parser.Parse(data,1)
  352. def check_data_buffer(self):
  353. if self.data_buffer:
  354. self._ptr.data.append(''.join(self.data_buffer))
  355. del self.data_buffer[:]
  356. self.data_buffer = None
  357. def destroy(self):
  358. """ Method used to allow class instance to be garbage-collected. """
  359. self.check_data_buffer()
  360. self._parser.StartElementHandler = None
  361. self._parser.EndElementHandler = None
  362. self._parser.CharacterDataHandler = None
  363. self._parser.StartNamespaceDeclHandler = None
  364. def starttag(self, tag, attrs):
  365. """XML Parser callback. Used internally"""
  366. self.check_data_buffer()
  367. self._inc_depth()
  368. self.DEBUG(DBG_NODEBUILDER, "DEPTH -> %i , tag -> %s, attrs -> %s" % (self.__depth, tag, repr(attrs)), 'down')
  369. if self.__depth == self._dispatch_depth:
  370. if not self._mini_dom :
  371. self._mini_dom = Node(tag=tag, attrs=attrs, nsp = self._document_nsp, node_built=True)
  372. else:
  373. Node.__init__(self._mini_dom,tag=tag, attrs=attrs, nsp = self._document_nsp, node_built=True)
  374. self._ptr = self._mini_dom
  375. elif self.__depth > self._dispatch_depth:
  376. self._ptr.kids.append(Node(tag=tag,parent=self._ptr,attrs=attrs, node_built=True))
  377. self._ptr = self._ptr.kids[-1]
  378. if self.__depth == 1:
  379. self._document_attrs = {}
  380. self._document_nsp = {}
  381. nsp, name = (['']+tag.split(':'))[-2:]
  382. for attr,val in list(attrs.items()):
  383. if attr == 'xmlns':
  384. self._document_nsp[''] = val
  385. elif attr.startswith('xmlns:'):
  386. self._document_nsp[attr[6:]] = val
  387. else:
  388. self._document_attrs[attr] = val
  389. ns = self._document_nsp.get(nsp, 'http://www.gajim.org/xmlns/undeclared-root')
  390. try:
  391. self.stream_header_received(ns, name, attrs)
  392. except ValueError as e:
  393. self._document_attrs = None
  394. raise ValueError(str(e))
  395. if not self.last_is_data and self._ptr.parent:
  396. self._ptr.parent.data.append('')
  397. self.last_is_data = 0
  398. def endtag(self, tag ):
  399. """XML Parser callback. Used internally"""
  400. self.DEBUG(DBG_NODEBUILDER, "DEPTH -> %i , tag -> %s" % (self.__depth, tag), 'up')
  401. self.check_data_buffer()
  402. if self.__depth == self._dispatch_depth:
  403. if self._mini_dom.getName() == 'error':
  404. self.streamError = self._mini_dom.getChildren()[0].getName()
  405. self.dispatch(self._mini_dom)
  406. elif self.__depth > self._dispatch_depth:
  407. self._ptr = self._ptr.parent
  408. else:
  409. self.DEBUG(DBG_NODEBUILDER, "Got higher than dispatch level. Stream terminated?", 'stop')
  410. self._dec_depth()
  411. self.last_is_data = 0
  412. if self.__depth == 0: self.stream_footer_received()
  413. def handle_cdata(self, data):
  414. """XML Parser callback. Used internally"""
  415. self.DEBUG(DBG_NODEBUILDER, data, 'data')
  416. if self.last_is_data:
  417. if self.data_buffer:
  418. self.data_buffer.append(data)
  419. elif self._ptr:
  420. self.data_buffer = [data]
  421. self.last_is_data = 1
  422. def handle_namespace_start(self, prefix, uri):
  423. """XML Parser callback. Used internally"""
  424. self.check_data_buffer()
  425. def DEBUG(self, level, text, comment=None):
  426. """ Gets all NodeBuilder walking events. Can be used for debugging if redefined."""
  427. def getDom(self):
  428. """ Returns just built Node. """
  429. self.check_data_buffer()
  430. return self._mini_dom
  431. def dispatch(self,stanza):
  432. """ Gets called when the NodeBuilder reaches some level of depth on it's way up with the built
  433. node as argument. Can be redefined to convert incoming XML stanzas to program events. """
  434. def stream_header_received(self,ns,tag,attrs):
  435. """ Method called when stream just opened. """
  436. self.check_data_buffer()
  437. def stream_footer_received(self):
  438. """ Method called when stream just closed. """
  439. self.check_data_buffer()
  440. def has_received_endtag(self, level=0):
  441. """ Return True if at least one end tag was seen (at level) """
  442. return self.__depth <= level and self.__max_depth > level
  443. def _inc_depth(self):
  444. self.__last_depth = self.__depth
  445. self.__depth += 1
  446. self.__max_depth = max(self.__depth, self.__max_depth)
  447. def _dec_depth(self):
  448. self.__last_depth = self.__depth
  449. self.__depth -= 1
  450. def XML2Node(xml):
  451. """ Converts supplied textual string into XML node. Handy f.e. for reading configuration file.
  452. Raises xml.parser.expat.parsererror if provided string is not well-formed XML. """
  453. return NodeBuilder(xml).getDom()
  454. def BadXML2Node(xml):
  455. """ Converts supplied textual string into XML node. Survives if xml data is cutted half way round.
  456. I.e. "<html>some text <br>some more text". Will raise xml.parser.expat.parsererror on misplaced
  457. tags though. F.e. "<b>some text <br>some more text</b>" will not work."""
  458. return NodeBuilder(xml).getDom()