Python ElementTree: Parsing a string and getting ElementTree instance

a 夏天 提交于 2019-12-09 05:06:13

问题


I have a string containing XML data that is returned from an http request.

I am using ElementTree to parse the data, and I want to then search recursively for an element.

According to this question, I can only search recursively with result.findall() if result is of type ElementTree rather than type Element.

Now xml.etree.ElementTree.fromstring() , used to parse the string, returns an Element object, while xml.etree.ElementTree.parse(), used to parse a file, returns an ElementTree object.

My question is then: How can I parse the string and get an ElementTree instance? (without any madness like writing to a temporary file)


回答1:


When you use ElementTree.fromstring() what you're getting back is basically the root of the tree, so if you create a new tree like this ElementTree.ElementTree(root) you'll get you're looking for.

So, to make it clearer:

from xml.etree import ElementTree
tree = ElementTree.ElementTree(ElementTree.fromstring(<your_xml_string>))

or:

from xml.etree.ElementTree import fromstring, ElementTree
tree = ElementTree(fromstring(<your_xml_string>))



回答2:


Turn your string into a file-like object and use ElementTree.parse:

from xml.etree import ElementTree
from cStringIO import StringIO

tree = ElementTree.parse(StringIO(string))


来源:https://stackoverflow.com/questions/8580234/python-elementtree-parsing-a-string-and-getting-elementtree-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!