0

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.

1
  • 1
    you can always do open('filename.xml', 'w').write(ET.dump(root)) Commented Jul 4, 2019 at 7:24

1 Answer 1

2

You need

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

You can also use

open('filename.xml', 'w').write(ET.dump(root))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.