posfan12
posfan12

Reputation: 2651

ElementTree write method

I am trying to write some XML to disk:

import xml.etree.ElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

ET.dump(root)
ET.write("filename.xml")

However I get the error AttributeError: 'module' object has no attribute 'write'

I can't figure out what module has the write attribute. All the examples I've seen online show the attribute as belonging to tree, but I don't know how to define tree. One source does this:

from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("index.xhtml")
tree.write("output.xhtml")

But I am not reading and parsing a file. Would appreciate some help, thanks.

Upvotes: 0

Views: 649

Answers (1)

furas
furas

Reputation: 142641

You need

tree = ET.ElementTree(root)
tree.write("filename.xml")

You can also use

open('filename.xml', 'w').write(ET.dump(root))

Upvotes: 2

Related Questions