如何完全从原始XML创建twisted.words.xish.domish.Element

时间:2010-01-19 12:26:28

标签: python xml twisted twisted.words

我很惊讶XML基本对象(twisted.words.xish.domish.Element)无法完全从XML字符串创建。最相似的方式是:

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)

但它会产生:

iq.toXml()

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

除了编写自己的IElement实现之外,有没有办法使用原始XML?

1 个答案:

答案 0 :(得分:1)

这就是我用于片段的内容,它改编自网络上的某些内容。

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()