Python ElementTree:解析字符串并获取 ElementTree 实例
我有一个包含从 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用 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 thisElementTree.ElementTree(root)
you'll get you're looking for.So, to make it clearer:
or:
将字符串转换为类似文件的对象并使用 ElementTree.parse:
Turn your string into a file-like object and use
ElementTree.parse
: