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

Gabriel Rossetti gabriel.rossetti at arimaz.com
Tue Sep 2 03:45:22 MDT 2008


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





More information about the Twisted-Python mailing list