Hi,
I am very very new to python and in my application I have to create an XML file.
Please any one help on this issue

Regards,
Naresh

Dani AI

Generated

A concise, practical follow-up that builds on this thread: asked how to create XML; demonstrated a quick raw-string write (useful for tiny tests but brittle), and pointed to lxml for more advanced needs. For most real-world cases the standard library xml.etree.ElementTree provides a safe, simple builder that handles escaping and lets the library produce a valid XML prolog and correct encoding.

from xml.etree.ElementTree import Element, SubElement, ElementTree

root = Element('note')
SubElement(root, 'to').text = 'Tove'
SubElement(root, 'from').text = 'Jani'
SubElement(root, 'heading').text = 'Reminder'
SubElement(root, 'body').text = "Don't forget me this weekend!"

ElementTree(root).write('note.xml', encoding='utf-8', xml_declaration=True)

Notes and practical tips:

  • ElementTree automatically escapes special characters in element text. Including xml_declaration=True and encoding='utf-8' ensures a proper XML prolog.
  • For pretty-printed output, use xml.dom.minidom to reformat or use lxml's pretty_print (lxml is a good choice when XPath, XSLT, CDATA, schema validation or better performance are required).
  • For very large documents avoid building the whole tree in memory; use incremental/streaming APIs (XMLGenerator or lxml incremental builder) or write to a temporary file and rename for atomic updates.
  • Validate against an XSD when structure matters; prefer library support (lxml/xmlschema) rather than manual checks.
  • Confirm editor/viewer encoding when opening the resulting file; mismatched encodings are a common source of confusion.

This guidance complements the quick examples already posted and gives a safer, maintainable path for creating XML in Python.

Recommended Answers

All 2 Replies

Well, even though I'm in a bad mood, I'm not going to just give you a link to the file module. Here's how you open, and create an xml file:

xml = """
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
filename = 'file.xml'
f = open(filename, 'w')
f.write(xml)
f.close()

I suggest that you read up on file formats and the python language for simple things like this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.