使用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. \')
继续阅读与本文标签相同的文章
下一篇 :
Typora入门
-
基于 APIGateway 打造生产级别的 Knative 服务
2026-05-18栏目: 教程
-
棱镜丨圆通回应“承诺达”解散:由直营模式改回加盟商授权经营
2026-05-18栏目: 教程
-
自从有了它,我在微信上吵架就没输过!
2026-05-18栏目: 教程
-
OTT终端不断地在全球范围扩展,未来万物互联不再是梦想
2026-05-18栏目: 教程
-
2019云栖大会 | 开源数据库界大神集体现身,邀你共同感受“开源魅力”
2026-05-18栏目: 教程
