来自字符串源的Python xml ElementTree?

问题:来自字符串源的Python xml ElementTree?

ElementTree.parse从文件读取,如果字符串中已经有XML数据,该如何使用?

也许我在这里错过了一些东西,但是必须有一种使用ElementTree的方法,而无需将字符串写出到文件中并再次读取它。

xml.etree.elementtree

The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?

Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.

xml.etree.elementtree


回答 0

如果您xml.etree.ElementTree.parse用于从文件中进行解析,则可以使用xml.etree.ElementTree.fromstring从文本中进行解析。

参见xml.etree.ElementTree

If you’re using xml.etree.ElementTree.parse to parse from a file, then you can use xml.etree.ElementTree.fromstring to parse from text.

See xml.etree.ElementTree


回答 1

您可以将文本解析为字符串,从而创建一个Element,并使用该Element创建ElementTree。

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

我刚遇到这个问题,而文档虽然完整,但对于parse()fromstring()方法之间用法的区别并不是很简单。

You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.


回答 2

你需要 xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)

You need the xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)

回答 3

io.StringIO是将XML放入xml.etree.ElementTree的另一种选择:

import io
f = io.StringIO(xmlstring)
tree = ET.parse(f)
root = tree.getroot()

因此,它不会影响假定的XML声明tree(尽管ElementTree.write()需要此声明)。请参见如何使用xml.etree.ElementTree编写XML声明

io.StringIO is another option for getting XML into xml.etree.ElementTree:

import io
f = io.StringIO(xmlstring)
tree = ET.parse(f)
root = tree.getroot()

Hovever, it does not affect the XML declaration one would assume to be in tree (although that’s needed for ElementTree.write()). See How to write XML declaration using xml.etree.ElementTree.