xml_builder.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import xml.etree.ElementTree as ET
  2. #pretty print method
  3. def indent(elem, level=0):
  4. i = "\n" + level*" "
  5. j = "\n" + (level-1)*" "
  6. if len(elem):
  7. if not elem.text or not elem.text.strip():
  8. elem.text = i + " "
  9. if not elem.tail or not elem.tail.strip():
  10. elem.tail = i
  11. for subelem in elem:
  12. indent(subelem, level+1)
  13. if not elem.tail or not elem.tail.strip():
  14. elem.tail = j
  15. else:
  16. if level and (not elem.tail or not elem.tail.strip()):
  17. elem.tail = j
  18. return elem
  19. #root element
  20. root = ET.Element('bookstore', {'specialty':'novel'})
  21. #book sub-element
  22. book = ET.SubElement(root, 'book', {'style':'autobiography'})
  23. author = ET.SubElement(book, 'author')
  24. firstName = ET.SubElement(author, 'first-name')
  25. firstName.text = 'Joe'
  26. lastName = ET.SubElement(author, 'last-name')
  27. lastName.text = 'Bob'
  28. award = ET.SubElement(author, 'award')
  29. award.text = 'Trenton Literary Review Honorable Mention'
  30. price = ET.SubElement(book, 'price')
  31. price.text = str(12)
  32. #magazine sub-element
  33. magazine = ET.SubElement(root, 'magazine', {'style':'glossy', 'frequency':'monthly'})
  34. price = ET.SubElement(magazine, 'price')
  35. price.text = str(12)
  36. subscription = ET.SubElement(magazine, 'subscription', {'price':'24', 'per':'year'})
  37. #write to file
  38. tree = ET.ElementTree(indent(root))
  39. tree.write('bookstore2.xml', xml_declaration=True, encoding='utf-8')