0

我很惊讶 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?

4

1 回答 1

1

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() 
于 2010-01-19T18:25:11.930 回答