#-*-coding:utf-8 -*-
# AUTHOR: J
# DATE: 2019/8/21
import xml.etree.ElementTree as ET
from xml.dom import minidom
# 生成一个标准xml
def makeANewXML():
# 新建一个1级标题template,{}括起来的可以添加属性
one_element = ET.Element("template",{'type':'日常病程记录','version':'1.0'})
# 新建一个2级标题root
two_element = ET.SubElement(one_element,"root")
for i in range(5):
# 新建一个3级标题element
three_element = ET.SubElement(two_element, "element", {'controlName': '居住地%d'%i})
# 新建一个4级标题text
four_element = ET.SubElement(three_element, "text")
# 给4级标签里面添加元素123
four_element.text = '北京%d'%i
# 将1级目录保存住
tree = ET.ElementTree(one_element)
# 保存成文件,文件名前可以指定路径保存,UTF-8保证可以解析中文,xml_declaration保留声明
tree.write("test.xml", encoding='utf-8', xml_declaration=True)
# 将对象生成字符串类型,便于永久化保存
tostring = ET.tostring(one_element,encoding='utf-8',method='xml')
# 用minidom可以让<?xml version="1.0" ?>出现协议
string = minidom.parseString(tostring).toxml() #打印在一行
a=string.encode("utf-8")
# 打印的格式好看点
toprettyxml = minidom.parseString(tostring).toprettyxml()
print(string)
print(toprettyxml)
makeANewXML()
python 创建标准xml--第四讲
最新推荐文章于 2023-09-26 19:05:45 发布