How to create twisted.words.xish.domish.Element entirely from raw XML
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='juick@juick.com' 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='juick@juick.com' id='id123' type='get'> <query xmlns='ht开发者_JAVA技巧tp://juick.com/query#messages' mid='123456'/> </iq></>"
Is there any way to use raw XML except writing my own IElement implementation?
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()
精彩评论