Python creates the xml file example

  • 2020-05-27 06:00:16
  • OfStack

This article demonstrates how Python creates xml files as an example. I will share it with you for your reference as follows:

This is an example of generating an xml file using the ElementTree related class library

# *-* coding=utf-8
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.etree.ElementTree import dump
from xml.etree.ElementTree import Comment
from xml.etree.ElementTree import tostring
import os
def CreateXml():
  book =ElementTree()
  purOrder =Element("PurchaseOrder")
  list = Element("account",{'idsn':'2390094'})
  item = Element("item1",{"sku":"abcd","qty":"4"})
  SubElement(item,"Name").text="Potato Smasher"
  SubElement(item,"Description").text="Smash Potatoes like never before"
  item = Element("item2",{"sku":"gfhi","qty":"40"})
  SubElement(item,"Description").text="My Country"
  return book
def indent(elem,level=0):
  i ="\n"+level*"  "
  print elem;
  if len(elem):
    if not elem.text or not elem.text.strip():
      elem.text = i + "  "
    for e in elem:
      print e
    if not e.tail or not e.tail.strip():
      e.tail =i
  if level and (not elem.tail or not elem.tail.strip()):
    elem.tail =i
  return elem
if __name__ == '__main__':
  book =CreateXml()
  #book.write("book2.xml","utf-8",True) #true is with xml declaration

PS: here are a few more online tools for you to use about xml:

Online XML/JSON interconversion tool:

Online formatting XML/ online compression XML:

XML online compression/formatting tools:

XML code online formatting beautification tool:

More about Python related topics: interested readers to view this site "Python xml data operation skill summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for you to design Python program.

Related articles: