本文介绍了Python ElementTree:解析字符串并获取ElementTree实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

根据,我只能使用 result.findall()如果结果的类型为 ElementTree 而不是类型 Element

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

现在 xml.etree.ElementTree.fromstring()用于解析字符串,返回 Element 对象,而 xml.etree.ElementTree.parse()用于解析 ,返回 ElementTree 对象。

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.

然后我的问题是:如何解析字符串并获取 ElementTree 实例?(不带任何m就像写一个临时文件一样)

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

推荐答案

使用 ElementTree.fromstring()您得到的基本上是树的根,因此,如果创建像这样的新树,则 ElementTree.ElementTree(root)

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.

因此,更清楚地说:

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

这篇关于Python ElementTree:解析字符串并获取ElementTree实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 19:14