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