views:

136

answers:

1

I was surprised that XML basic object (twisted.words.xish.domish.Element) could not be created entirely from XML string. The most alike way is:

msg = "<iq to='[email protected]' id='id123' type='get'> \
            <query xmlns='http://juick.com/query#messages' mid='123456'/> \
       </iq>"
iq = domish.Element(('',''))
iq.addRawXml(msg)

But it generates:

iq.toXml()

u"<><iq to='[email protected]' id='id123' type='get'>             <query xmlns='http://juick.com/query#messages' mid='123456'/>        </iq></>"

Is there any way to use raw XML except writing my own IElement implementation?

+1  A: 

This is what I use for fragments, adapted from something found on the web somewhere.

from twisted.words.xish import domish

class ElementParser(object):
    "callable class to parse XML string into Element"

    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)
        parser.parse(tmp.toXml())
        return self.result.firstChildElement() 
Karl Anderson