xml.etree.ElementTree.Element'对象没有属性'write' [英] xml.etree.ElementTree.Element' object has no attribute 'write'
问题描述
我想读取一个XML字符串,对其进行编辑并将其另存为XML文件.
I want to read a XML string, edit it and save it as a XML file.
但是,当我执行 .write()
我发现,当您使用 ElementTree.fromstring(string)
读取XML字符串时,它将创建一个 ElementTree.Element
而不是一个 ElementTree 代码>本身.元素没有写方法,但是元素树有.
I found out that when you read an XML string using ElementTree.fromstring(string)
it will create an ElementTree.Element
and not an ElementTree
itself. An Element has no write method but the ElementTree does.
如何将元素写入XML文件?或者如何创建ElementTree并将其添加到ElementTree中,然后使用 .write
方法?
How can I write an Element to a XML file? Or how can I create an ElementTree and add my Element to that and then use the .write
method?
推荐答案
我发现,当您使用
ElementTree.fromstring(string)
读取xml字符串时,它实际上将创建ElementTree.Element
而不是ElementTree
本身.
I found out that when you read a xml string using
ElementTree.fromstring(string)
it will actually create anElementTree.Element
and not aElementTree
itself.
是的,您可以返回顶级元素(也称为文档元素").
Yes, you get the top-level element back (also called the "document element").
元素没有
write
方法,但是ElementTree
有.
The ElementTree
constructor signature goes like this:
class xml.etree.ElementTree.ElementTree(element=None, file=None)
因此非常简单:
import xml.etree.ElementTree as ET
doc = ET.fromstring("<test>test öäü</test>")
tree = ET.ElementTree(doc)
tree.write("test.xml", encoding="utf-8")
在编写XML文件时,始终应指定编码.大多数情况下,UTF-8是最佳选择.
You always should specify the encoding when writing an XML file. Most of the time, UTF-8 is the best choice.
这篇关于xml.etree.ElementTree.Element'对象没有属性'write'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!