Python ElementTree:解析字符串并获取 ElementTree 实例

发布于 2024-12-22 04:38:17 字数 703 浏览 1 评论 0原文

我有一个包含从 http 请求返回的 XML 数据的字符串。

我正在使用 ElementTree 来解析数据,然后我想递归地搜索一个元素。

根据这个问题,我只能用结果递归搜索。 findall() 如果 result 的类型为 ElementTree 而不是 Element 类型。

现在,用于解析字符串的 xml.etree.ElementTree.fromstring() 返回一个 Element 对象,而 xml.etree.ElementTree.parse()< /code>,用于解析文件,返回一个ElementTree对象。

我的问题是:如何解析字符串并获取 ElementTree 实例?(没有像写入临时文件这样的疯狂操作)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽清梦 2024-12-29 04:38:17

当您使用 ElementTree.fromstring() 时,您返回的基本上是树的根,因此如果您创建像这样的新树 ElementTree.ElementTree(root) 你会得到你正在寻找的。

因此,为了更清楚地说明:

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

或者:

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

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>))
我不吻晚风 2024-12-29 04:38:17

将字符串转换为类似文件的对象并使用 ElementTree.parse:

from xml.etree import ElementTree
from cStringIO import StringIO

tree = ElementTree.parse(StringIO(string))

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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文