網站首頁 編程語言 正文
PYTHON 操作 XML
讀取XML文件
關于XML的介紹
<data> 與 </data> 是一對標簽的開始與結束
<property … /> 也是一個正確的標簽,以 /> 結尾,是在標簽沒有嵌套內容時的簡寫形式
name=“cat”,name是<data>標簽的一個屬性,cat是name屬性的值
description here …是<data>標簽的內容,這里是一段文本。當然也可以是xml的嵌套
<data name="cat" num="10"> description here ... </data> <property value="node" /> <country name="china"> <province name="beijing"> <school name="the sunshine school" /> </province> </country>
準備一個demo.xml文件
<data> <teacher name="Albert"> <birthday>1980</birthday> <gender>male</gender> <subject>Math</subject> </teacher> <student name="Becky"> <birthday>2000</birthday> <gender>female</gender> <hobbies> <hobby>skating</hobby> <hobby>rocks</hobby> </hobbies> <exam absence="no"> <math>90</math> <english>90</english> <music>95</music> </exam> </student> <student name="Cindy"> <birthday>2001</birthday> <gender>female</gender> <hobbies> <hobby>reading</hobby> <hobby>guitar</hobby> </hobbies> <exam absence="yes"> </exam> </student> <student name="Duke"> <birthday>2000</birthday> <gender>male</gender> <hobbies> <hobby>football</hobby> <hobby>surfing</hobby> </hobbies> <exam absence="no"> <math>100</math> <english>80</english> <music>92</music> </exam> </student> </data>
讀取xml文件內容
# Read the .xml file
tree = ET.parse("demo.xml")
root = tree.getroot()
print(root)
結果
<Element 'data' at 0x102d80cf8>
遍歷XML元素
for … in … 可以遍歷當前元素的所有直接子節點
for n in root:
# items() returns all <key, value> pairs of the tag
print(n, n.tag , n.attrib, n.items())
結果
(<Element 'teacher' at 0x1048b9e48>, 'teacher', {'name': 'Albert'}, [('name', 'Albert')])
(<Element 'student' at 0x1048bf0f0>, 'student', {'name': 'Becky'}, [('name', 'Becky')])
(<Element 'student' at 0x1048bf3c8>, 'student', {'name': 'Cindy'}, [('name', 'Cindy')])
(<Element 'student' at 0x1048bf5f8>, 'student', {'name': 'Duke'}, [('name', 'Duke')])
想要迭代遍歷當前元素的所有子節點(包括子孫節點)
for n in root.iter():
print(n, n.tag)
結果
(<Element 'data' at 0x1052f0cf8>, 'data')
(<Element 'teacher' at 0x1052f0e48>, 'teacher')
(<Element 'birthday' at 0x1052f0d30>, 'birthday')
(<Element 'gender' at 0x1052f6080>, 'gender')
(<Element 'subject' at 0x1052f60b8>, 'subject')
(<Element 'student' at 0x1052f60f0>, 'student')
(<Element 'birthday' at 0x1052f6048>, 'birthday')
(<Element 'gender' at 0x1052f6128>, 'gender')
(<Element 'hobbies' at 0x1052f6198>, 'hobbies')
(<Element 'hobby' at 0x1052f6208>, 'hobby')
(<Element 'hobby' at 0x1052f6240>, 'hobby')
(<Element 'exam' at 0x1052f62b0>, 'exam')
(<Element 'math' at 0x1052f6320>, 'math')
(<Element 'english' at 0x1052f6390>, 'english')
(<Element 'music' at 0x1052f6400>, 'music')
(<Element 'student' at 0x1052f63c8>, 'student')
(<Element 'birthday' at 0x1052f6438>, 'birthday')
(<Element 'gender' at 0x1052f6470>, 'gender')
(<Element 'hobbies' at 0x1052f64a8>, 'hobbies')
(<Element 'hobby' at 0x1052f6518>, 'hobby')
(<Element 'hobby' at 0x1052f6588>, 'hobby')
(<Element 'exam' at 0x1052f65c0>, 'exam')
(<Element 'student' at 0x1052f65f8>, 'student')
(<Element 'birthday' at 0x1052f6630>, 'birthday')
(<Element 'gender' at 0x1052f6668>, 'gender')
(<Element 'hobbies' at 0x1052f66a0>, 'hobbies')
(<Element 'hobby' at 0x1052f6710>, 'hobby')
(<Element 'hobby' at 0x1052f6780>, 'hobby')
(<Element 'exam' at 0x1052f67b8>, 'exam')
(<Element 'math' at 0x1052f6828>, 'math')
(<Element 'english' at 0x1052f6898>, 'english')
(<Element 'music' at 0x1052f6908>, 'music')
想要選擇性地迭代直接子節點
for n in root.iter('teacher'):
print(n, n.tag)
(<Element 'teacher' at 0x100f29e48>, 'teacher')
查找XML元素
find與findall查找xml元素
# find the first element
print(root.find('student'))
# find all elements
print(root.findall('student'))
<Element 'student' at 0x1034300f0>
[<Element 'student' at 0x1034300f0>, <Element 'student' at 0x1034303c8>, <Element 'student' at 0x1034305f8>]
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)
結果
? ? <student name="Cindy">
? ? ? ? <birthday>2001</birthday>
? ? ? ? <gender>female</gender>
? ? ? ? <hobbies>
? ? ? ? ? ? <hobby>reading</hobby>
? ? ? ? ? ? <hobby>guitar</hobby>
? ? ? ? </hobbies>
? ? ? ? <exam absence="no">
? ? ? ? <math>90</math><music>90</music></exam>
? ? </student>
修改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)
結果
? ? <student name="Cindy">
? ? ? ? <birthday>2001</birthday>
? ? ? ? <gender>female</gender>
? ? ? ? <hobbies>
? ? ? ? ? ? <hobby>piano</hobby>
? ? ? ? ? ? <hobby old_hobby="yes">reading</hobby></hobbies>
? ? ? ? <exam absence="no" date="2022-11-11">
? ? ? ? <math>90</math><music>90</music></exam>
? ? </student>
原文鏈接:https://blog.csdn.net/qq_52883908/article/details/127771369
相關推薦
- 2022-05-18 C語言?動態內存開辟常見問題解決與分析流程_C 語言
- 2022-09-07 基于域名的方式訪問Istio服務網格中的多個應用程序的方法詳解_相關技巧
- 2022-05-12 tp6 app接口集成Swagger生成接口文檔
- 2022-06-04 Android自定義ScrollView實現阻尼回彈_Android
- 2022-09-23 C#實現自定義光標并動態切換_C#教程
- 2022-09-09 通過jmeter壓測surging的方法_實用技巧
- 2022-07-08 C#使用GDI+實現生成驗證碼_C#教程
- 2022-09-07 Golang?中?omitempty的作用_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支