本文介绍了xml.etree.ElementTree.Element'对象没有属性'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?

推荐答案

是的,您可以返回顶级元素(也称为文档元素").

Yes, you get the top-level element back (also called the "document element").

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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 23:00