使用python元素树解析 文件

<?  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  .etree.ElementTree as ET

tree = ET.ElementTree(file=\"target. \")
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. \')
收藏 打印