xml处理模块

1.root是节点,起始的数据。

child.tag 和i.tag 返回的都是经过for循环得到的数据,后面的child.attrib和i.text是字符串输出格式。attrib是字典,text是文本。

import xml.etree.ElementTree as ET

tree = ET.parse("xml test")    #打开xml test 文件

root = tree.getroot()

print(root)

print(root.tag)   # 输出为data
for child in root:
    print("------------------",child.tag,child.attrib)
    for i in child:
        print(i.tag,i.text)  


结果如下:
<Element 'data' at 0x00000254E9B47638data>
data

------------------ country {'name': 'Liechtenstein'}
rank 2
year 2008
gdppc 141100
neighbor None
neighbor None
------------------ country {'name': 'Singapore'}
rank 5
year 2011
gdppc 59900
neighbor None
------------------ country {'name': 'Panama'}
rank 69
year 2011
gdppc 13600
neighbor None
neighbor None                                                                                
                                                                                     
----------------------------------------------------华丽的分割线-------------------------------------------------------------

想获取root里的某一项属性,可以通过iter。

for node in root.iter("year"):
    print(node.tag,node.text)
    
# year 2008
# year 2011
# year 2011
                                                                                                                                   

修改xml里的值


for node in root.iter("year"):
    new_node = int(node.text) + 1
    node.text = str(new_node)
    node.set("updated","yes")

tree.write("xml test")

 

删除rank点数大于50的

for country in root.findall("country"):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)

tree.write("output.xml")

  

  

 
posted @ 2018-04-17 21:59  Roc_Atlantis  阅读(176)  评论(0编辑  收藏  举报