2022年 11月 4日

python 创建xml文件

  1. #encoding:utf-8
  2. from xml.dom.minidom import Document
  3. doc = Document() #创建DOM文档对象
  4. item = doc.createElement('DOCUMENT') #创建根元素
  5. item.setAttribute('content_method',"full")#设置命名空间
  6. #引用本地XML Schema
  7. doc.appendChild(item)
  8. # # ############item:Python处理XML之Minidom################
  9. # item = doc.createElement('item')
  10. # item.setAttribute('genre','XML')
  11. # DOCUMENT.appendChild(item)
  12. # 设置阈值
  13. key = doc.createElement('thresholdValue')
  14. key_text = doc.createTextNode('28') #元素内容写入
  15. key.appendChild(key_text)
  16. # DOCUMENT.appendChild(item)
  17. item.appendChild(key)
  18. # 设置一个像素代表多少mm
  19. DPI_value = doc.createElement('DPI')
  20. price_text = doc.createTextNode('0.025')
  21. DPI_value.appendChild(price_text)
  22. item.appendChild(DPI_value)
  23. display = doc.createElement('display')
  24. item.appendChild(display)
  25. display_url = doc.createElement('url')
  26. display_title = doc.createElement('title')
  27. display_url_text = doc.createTextNode('https://www.baidu.com/')
  28. display_title_text = doc.createTextNode('Good')
  29. display.appendChild(display_url)
  30. display.appendChild(display_title)
  31. display_url.appendChild(display_url_text)
  32. display_title.appendChild(display_title_text)
  33. item.appendChild(display)
  34. ########### 将DOM对象doc写入文件
  35. f = open('config.xml','w')
  36. #f.write(doc.toprettyxml(indent = '\t', newl = '\n', encoding = 'utf-8'))
  37. doc.writexml(f,indent = '\t',newl = '\n', addindent = '\t',encoding='utf-8')
  38. f.close()
  39. print("Fine")