How To Create XML File In Python
Chapter:
Python
Last Updated:
23-04-2023 04:44:18 UTC
Program:
/* ............... START ............... */
import xml.etree.ElementTree as ET
# Create the root element
root = ET.Element('root')
# Create a child element and add it to the root
child = ET.SubElement(root, 'child')
child.text = 'This is the child element'
# Create another child element and add it to the root
child2 = ET.SubElement(root, 'child2')
child2.text = 'This is the second child element'
# Create the XML tree
tree = ET.ElementTree(root)
# Write the tree to a file
tree.write('example.xml')
/* ............... END ............... */
Output
<root>
<child>This is the child element</child>
<child2>This is the second child element</child2>
</root>
Notes:
-
The program creates an XML file using the Python programming language.
- It starts by importing the xml.etree.ElementTree module, which provides a simple way to work with XML data in Python.
- The program then creates a root element called root using the Element function provided by the ElementTree module. It then creates two child elements called child and child2 using the SubElement function and adds them to the root element.
- The program sets the text content of each child element using the text attribute of the Element objects. In this example, we set the text to "This is the child element" for the first child element, and "This is the second child element" for the second child element.
- Finally, the program creates an ElementTree object with the root element and writes the tree to a file using the write function of the ElementTree module. The file is named example.xml.
- The resulting XML file has a root element called root with two child elements called child and child2, each with their respective text content.
Tags
python program to create xml file #How To Create XML File In Python #Create XML file Python ElementTree