PYTHON 操作 XML
读取XML文件
关于XML的介绍
与 是一对标签的开始与结束
name=“cat”,name是标签的一个属性,cat是name属性的值
description here …是标签的内容,这里是一段文本。当然也可以是xml的嵌套
description here ...
准备一个demo.xml文件
1980 male Math 2000 female skating rocks 90 95 2001 female reading guitar 2000 male football surfing 80 92
读取xml文件内容
# Read the .xml file tree = ET.parse("demo.xml") root = tree.getroot() print(root)
结果
遍历XML元素
for … in … 可以遍历当前元素的所有直接子节点
for n in root: # items() returns allpairs of the tag print(n, n.tag , n.attrib, n.items())
结果
(
, 'teacher', {'name': 'Albert'}, [('name', 'Albert')])
(, 'student', {'name': 'Becky'}, [('name', 'Becky')])
(, 'student', {'name': 'Cindy'}, [('name', 'Cindy')])
(, 'student', {'name': 'Duke'}, [('name', 'Duke')])
想要迭代遍历当前元素的所有子节点(包括子孙节点)
for n in root.iter(): print(n, n.tag)
结果
(
, 'data')
(, 'teacher')
(, 'birthday')
(, 'gender')
(, 'subject')
(, 'student')
(, 'birthday')
(, 'gender')
(, 'hobbies')
(, 'hobby')
(, 'hobby')
(, 'exam')
(, 'math')
(, 'english')
(, 'music')
(, 'student')
(, 'birthday')
(, 'gender')
(, 'hobbies')
(, 'hobby')
(, 'hobby')
(, 'exam')
(, 'student')
(, 'birthday')
(, 'gender')
(, 'hobbies')
(, 'hobby')
(, 'hobby')
(, 'exam')
(, 'math')
(, 'english')
(, 'music')
想要选择性地迭代直接子节点
for n in root.iter('teacher'): print(n, n.tag)
(, 'teacher')
查找XML元素
find与findall查找xml元素
# find the first element print(root.find('student')) # find all elements print(root.findall('student'))
[ , , ]
demo
for n in root: if n.tag == 'student' and n.get('name') == 'Becky': exam_node = n.find('exam') for subject in exam_node: print(subject.tag + " " + subject.text)
结果
math 90
english 90
music 95
添加XML元素
p = ET.Element(tag_name)
demo
for n in root: if n.tag == 'student' and n.get('name') == 'Cindy': exam_node = n.find('exam') exam_node.set("absence", "no") for subject in ['math', 'music']: p = ET.Element(subject) p.text = '90' exam_node.append(p) if os.path.exists('new.xml'): os.remove('new.xml') tree.write('new.xml', encoding='utf-8', xml_declaration=True)
结果
2001
female
reading
guitar
90
修改XML元素
demo
for n in root: if n.tag == 'student' and n.get('name') == 'Cindy': exam_node = n.find('exam') exam_node.set("absence", "no") exam_node.set("date", "2022-11-11") for subject in ['math', 'music']: p = ET.Element(subject) p.text = '90' exam_node.append(p) hobbies_node = n.find('hobbies').findall("hobby") hobbies_node[0].text = 'piano' p = ET.Element("hobby") p.set("old_hobby", 'yes') p.text = 'reading' n.find('hobbies').remove(hobbies_node[1]) n.find('hobbies').append(p)
结果
2001
female
piano
reading
90
到此这篇关于Python对XML文件实现增删改查操作的文章就介绍到这了,更多相关Python XML增删改查内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!