Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xml.etree.ElementTree.Element' object has no attribute 'write'

I want to read a XML string, edit it and save it as a XML file.

However I get the mentioned error in the title when I do .write()

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.

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?

like image 257
user180146 Avatar asked Jul 15 '26 03:07

user180146


1 Answers

I found out that when you read a xml string using ElementTree.fromstring(string) it will actually create an ElementTree.Element and not a ElementTree itself.

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

An Element has no write method but the ElementTree does.

The ElementTree constructor signature goes like this:

class xml.etree.ElementTree.ElementTree(element=None, file=None)

Therefore it's completely straightforward:

import xml.etree.ElementTree as ET

doc = ET.fromstring("<test>test öäü</test>")

tree = ET.ElementTree(doc)
tree.write("test.xml", encoding="utf-8")

You always should specify the encoding when writing an XML file. Most of the time, UTF-8 is the best choice.

like image 162
Tomalak Avatar answered Jul 17 '26 15:07

Tomalak