[Twisted-Python] create new domish.Element from string XML

Gabriel Rossetti gabriel.rossetti at arimaz.com
Wed Sep 3 08:59:58 MDT 2008

Gabriel Rossetti wrote:
> Gabriel Rossetti wrote:
>> Hello everyone,
>> I sometimes have to create domish.Element from a string and I can't 
>> find any way of doing this. I saw that I can add children from a 
>> string but not create a whole XML tree.
>> Is there a way of doing this other than creating a dummy element, 
>> adding the XML string as a child and then extracting the child?
>> Thank you,
>> Gabriel
> I tried creating a dummy element, adding the raw string as a child 
> using "addRawXml()" and then extracting the first child, and this does 
> not work because the raw xml string is just added without being 
> parsed. I write this up, if anybody is interested, that does what I 
> need. If a better method exists, please tell me.
> Gabriel
> # 
> ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 
> def rawXmlToElement(s):
>    """
>    Turn a raw string XML document into a XML element
>      @param s: the raw string XML document
>    @type s: C{str}
>      @return: the XML element
>    @rtype: 
> U{twisted.words.xish.domish.Element<http://twistedmatrix.com/documents/current/api/twisted.words.xish.domish.Element.html>} 
>      @raise ParserError: if there was an error parsing the raw string 
> XML document
>    """
>    result = None
>    def onStart(el):
>        result = el
>    def onEnd():
>        pass
>    def onElement(el):
>        result.addChild(el)
>          parser = domish.elementStream()
>    parser.DocumentStartEvent = onStart
>    parser.ElementEvent = onElement
>    parser.DocumentEndEvent = onEnd
>    parser.parse(s)
>      return result
Hmmm, this code worked when I posted it, and it no longer does... maybe 
the interpreter I was testing it in had an old version cached, but now 
it tells me that "result" is None when "onElement" is called, what I 
don't get is that a clusure should have been created with those internal 
functions, no? When "DocumentStartEvent" is called, It does set 
"result", but when "ElementEvent" is called, "result" no longer exists. 
Does anyone know what's going on?

Thank you,

More information about the Twisted-Python mailing list