I created an xml tree with something like this
top = Element('top')
child = SubElement(top, 'child')
child.text = 'some text'
how do I dump it into an XML file? I tried top.write(filename)
, but the method doesn't exist.
Creating XML Document using Python First, we import minidom for using xml. dom . Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks.
The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.
To summarize: An XML file is a file used to store data in the form of hierarchical elements. Data stored in XML files can be read by computer programs with the help of custom tags, which indicate the type of element.
You need to instantiate an ElementTree
object and call write()
method:
import xml.etree.ElementTree as ET
top = ET.Element('top')
child = ET.SubElement(top, 'child')
child.text = 'some text'
tree = ET.ElementTree(top)
tree.write('output.xml')
The contents of the output.xml
after running the code:
<top><child>some text</child></top>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With