diff src/tools/xml_tools.py @ 289:0e54b1b0a8c8

xml_tools: added ElementParser for raw xml -> domish.Element conversion
author Goffi <goffi@goffi.org>
date Sun, 06 Feb 2011 23:40:29 +0100
parents b1794cbb88e5
children e04ccf122bb6
line wrap: on
line diff
--- a/src/tools/xml_tools.py	Sun Feb 06 23:32:13 2011 +0100
+++ b/src/tools/xml_tools.py	Sun Feb 06 23:40:29 2011 +0100
@@ -23,6 +23,7 @@
 from xml.dom import minidom
 from wokkel import data_form
 import pdb
+from twisted.words.xish import domish
 
 """This library help manage XML used in SàT (parameters, registration, etc) """
 
@@ -300,3 +301,28 @@
     def toXml(self):
         """return the XML representation of the panel""" 
         return self.doc.toxml()
+
+
+
+class ElementParser(object):
+    """callable class to parse XML string into Element
+    Found at http://stackoverflow.com/questions/2093400/how-to-create-twisted-words-xish-domish-element-entirely-from-raw-xml/2095942#2095942
+    (c) Karl Anderson"""
+
+    def __call__(self, s):
+        self.result = None
+        def onStart(el):
+            self.result = el
+        def onEnd():
+            pass
+        def onElement(el):
+            self.result.addChild(el)
+
+        parser = domish.elementStream()
+        parser.DocumentStartEvent = onStart
+        parser.ElementEvent = onElement
+        parser.DocumentEndEvent = onEnd
+        tmp = domish.Element(("", "s"))
+        tmp.addRawXml(s.replace('\n','').replace('\t',''))
+        parser.parse(tmp.toXml())
+        return self.result.firstChildElement()