一: XML文件格式介绍:
<tag attrib = > text </tag> tail
例:<APP_KEY channel = 'CSDN'> hello123456789 </APP_KEY>
- tag,即标签,用于标识该元素表示哪种数据,即APP_KEY
- attrib,即属性,用Dictionary形式保存,即{‘channel’ = ‘CSDN’}
- text,文本字符串,可以用来存储一些数据,即hello123456789
- tail,尾字符串,并不是必须的,例子中没有包含。
二 :生成xml文件
from xml.etree import ElementTree as ET
def create_name_same(el):
li = []
for i in range(10):
li.append(ET.SubElement(el, 'case'))
return li
def create_name_not(el):
ET.SubElement(el, 'name')
ET.SubElement(el, 'yyy')
ET.SubElement(el, 'xxx')
root = ET.Element('tasks')
sub1 = ET.SubElement(root, 'cases')
sub2 = ET.SubElement(root, 'name')
li_sub1_sub_node = create_name_same(sub1)
for sub1_sub_node in li_sub1_sub_node:
create_name_not(sub1_sub_node)
print(ET.dump(root))
tree = ET.ElementTree(root)
tree.write("/root/桌面/asd/aaa.xml", encoding='utf-8', xml_declaration=True)
xml_string = ET.tostring(root)
from xml.dom import minidom
dom = minidom.parseString(xml_string)
with open("/root/桌面/asd/aaa.xml", 'w', encoding='utf-8') as f:
dom.writexml(f, addindent='\t', newl='\n', encoding='utf-8')
dom.toxml()
dom.toprettyxml()
type(dom.toprettyxml())
"""
<?xml version="1.0" encoding="utf-8"?>
<tasks>
<cases>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
<case>
<name/>
<yyy/>
<xxx/>
</case>
</cases>
<name/>
</tasks>
"""
解析xml
from xml.etree import ElementTree as ET
path = "/root/桌面/asd/aaa.xml"
tree = ET.parse(path)
root = tree.getroot()
nel = root.findall('./cases/case')
for i in nel:
i.text = str(111)
nel = root.find('./cases/case')
for i in nel:
i.text = str(222)
xml_string = ET.tostring(root).replace(b'\t', b'').replace(b'\n', b'')
from xml.dom import minidom
dom = minidom.parseString(xml_string)
with open("/root/桌面/asd/aaa.xml", 'w', encoding='utf-8') as f:
dom.writexml(f, addindent='\t', newl='\n', encoding='utf-8')
"""
<?xml version="1.0" encoding="utf-8"?>
<tasks>
<cases>
<case>
111
<name>222</name>
<yyy>222</yyy>
<xxx>222</xxx>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
<case>
111
<name/>
<yyy/>
<xxx/>
</case>
</cases>
<name/>
</tasks>
"""