【XML】python解析XML

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tfcy694/article/details/85071723

使用python元素树解析XML文件

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
import xml.etree.ElementTree as ET

tree = ET.ElementTree(file="target.xml")
root = tree.getroot()
print(root)

for child in root:
    if child.tag == 'country':
    	child.remove(child[0])		#删除子元素
    	child[0].text = '100'		#利用int索引修改rank元素,不得使用字典索引
    	child[0].set('000','111')	#设置新属性 元素属性不得多余1个
   		child.append(root[0][1])	#增加子元素
   		child.remove(child[0])		#删除子元素

tree.write('target1.xml')

猜你喜欢

转载自blog.csdn.net/tfcy694/article/details/85071723