Home >Backend Development >Python Tutorial >How Can You Create a Simple XML File in Python Using the ElementTree API?
Creating a Simple XML File in Python
Creating XML files in Python offers multiple approaches, with various libraries available. This article explores these options and provides a detailed solution using the ElementTree API.
ElementTree:
Introduced in Python 2.5, ElementTree is the most commonly employed XML library. It's an easy-to-use, pure-Python implementation that provides a straightforward API.
Available Options:
Example Using cElementTree:
To generate the specified XML document using cElementTree:
<code class="python">import xml.etree.cElementTree 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" tree = ET.ElementTree(root) tree.write("filename.xml")</code>
This code creates the desired XML structure and writes it to a file named "filename.xml."
Further Reading:
Additional Notes:
The above is the detailed content of How Can You Create a Simple XML File in Python Using the ElementTree API?. For more information, please follow other related articles on the PHP Chinese website!