日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python讀寫xml文件實例詳解嘛_python

作者:單單一個越字 ? 更新時間: 2022-05-03 編程語言

xml文件:country.xml


	231
		1This is NEW
		2008
		141100
		  
		
	
	
		4
		2011
		59900
		
	
	
		68
		2011
		13600
		
		
	
	
	

xml文件解讀

1.xml一個節點有三個屬性:tag、text、attrib
2. 以第一個子節點country為例:
3. tag代表節點名字,country節點的tag就是它的名字:country
4. text代表節點文本內容,rank節點的text就是1
5. attrib代表節點包含的屬性,以{屬性:值}這樣的字典形式存放。country節點的屬性是{name:Liechtenstein}.name是屬性的鍵,Liechtenstein是屬性的值。{屬性:值}就是一個字典類型,可以使用一切字典方法。
6. country節點的tag為country,attrib為{name:Liechtenstein},text為空
7. rank節點的tag為rank,attrib為空字典,text為1
8. 綜上所述,xml文檔主要由節點以及節點的三個屬性組成。

讀取文件:

import xml.etree.ElementTree as ET
file_path = r'xml_te.xml'
tree = ET.ElementTree(file = file_path)  #讀取xml文件
print(tree.iter())
for i in tree.iter('rank'):  #迭代獲取tag為'rank'的節點
    print(i.text)
nodes = tree.find('country') #獲取第一個tag為country的節點,返回是子節點的迭代對象
print(nodes.tag)
nodes2 = tree.findall('country') #獲取所有tag為country的節點
print(nodes2)
for node in nodes2:
    #打印節點的三個屬性
    print(node.tag)
    print(node.attrib)
    print(node.text)

增加新節點及修改屬性值和文本

import xml.etree.ElementTree as ET
file_path = r'xml_te.xml'
tree = ET.ElementTree(file = file_path)  #讀取xml文件

# root = tree.getroot()  #獲取根結點
"""增加新節點"""
net = ET.Element('NewNode')
net.attrib = {'A':"1"}   #節點屬性
net.text = "This is NEW"   #節點文本
node = tree.find('country/rank/NewNode')   #找到需要增加子節點的父節點
node.append(net)
print(node.text)
tree.write(file_path)  #寫入文件
"""修改屬性值"""
sub = tree.find('country')   #找到節點
sub.set('name',"shdi2hajk")  #set(key,new value)
sub.text = '231'
print(sub.attrib)
print(sub.text)
tree.write(file_path)  #寫入文件

總結

原文鏈接:https://blog.csdn.net/qq_38122800/article/details/123208245

欄目分類
最近更新