Python3 xml模塊的增刪改查


xml數據示例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<data>
     <country name = "Liechtenstein" >
         <rank updated = "yes" > 2 < / rank>
         <year updated_by = "Alex" > 2009 < / year>
         <gdppc> 141100 < / gdppc>
         <neighbor direction = "E" name = "Austria" / >
         <neighbor direction = "W" name = "Switzerland" / >
     < / country>
     <country name = "Singapore" >
         <rank updated = "yes" > 5 < / rank>
         <year updated_by = "Alex" > 2012 < / year>
         <gdppc> 59900 < / gdppc>
         <neighbor direction = "N" name = "Malaysia" / >
     < / country>
     <country name = "Panama" >
         <rank updated = "yes" > 69 < / rank>
         <year updated_by = "Alex" > 2012 < / year>
         <gdppc> 13600 < / gdppc>
         <neighbor direction = "W" name = "Costa Rica" / >
         <neighbor direction = "E" name = "Colombia" / >
         <info>
             <population> 8 < / population>
             <size> 960 < / size>
         < / info>
     < / country>
< / data>

xml數據處理

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import xml.etree.ElementTree as ET
 
'''xml 數據的處理 '''
tree = ET.parse( "xmltest.xml" )
root = tree.getroot() #數據內存地址
print (root.tag)  #標簽
 
'''遍歷所有數據'''
for i in root:
     print (i.tag,i.attrib)  #attrib 獲取屬性名
     for k in i:
         print (k.tag,k.attrib,k.text) #text 文本內容
 
''' 遍歷某一個標簽的值 '''
for ta in root. iter ( "year" ):
     print (ta.tag,ta.attrib,ta.text)

XML數據的創建

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'''xml 數據的創建 '''
new_xml = ET.Element( "personinfolist" ) #Element 根節點
personinfo = ET.SubElement(new_xml, "personinfo" , attrib = { "enrolled" : "yes" })
name = ET.SubElement(personinfo, "name" #SubElement 子節點
name.text = "Alex Li"
age = ET.SubElement(personinfo, "age" , attrib = { "checked" : "no" })
sex = ET.SubElement(personinfo, "sex" )
age.text = '56'
personinfo2 = ET.SubElement(new_xml, "personinfo" , attrib = { "enrolled" : "no" })
name = ET.SubElement(personinfo2, "name" )
name.text = "Oldboy Ran"
age = ET.SubElement(personinfo2, "age" )
age.text = '19'
 
et = ET.ElementTree(new_xml)  # 生成文檔對象
et.write( "test.xml" , encoding = "utf-8" , xml_declaration = True )
""" xml_declaration 聲明xml文件類型 """
ET.dump(new_xml)  # 打印生成的格式

XML數據的修改

?
1
2
3
4
5
6
7
8
9
10
11
12
13
'''xml 數據的修改 '''
for node in root. iter ( 'year' ):
     new_year = int (node.text) + 1
     node.text = str (new_year)
     node. set ( "updated_by" , "Alex" )
tree.write( "xmltest.xml" )
 
# 刪除node
for country in root.findall( 'country' ):
     rank = int (country.find( 'rank' ).text)
     if rank > 50 :
         root.remove(country)
tree.write( 'output.xml' )


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM