OS文件

<?xml version="1.0" encoding="UTF-8" ?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</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.parse("mm.xml")
# 加载想要读取的文件

root = tree.getroot() # 获取根节点
print('tag:',root.tag)    # .tag 节点标签名
print("attrib:",root.attrib) # .attrib  节点标签的属性,属性名和属性值是键值对形式,多个属性对用空格分隔
print("text:",root.text)   # .text 节点标签的内容

node1 = root.find("country")  # 查找节点 第一个 country
print(node1.attrib)

node2 = root.findall("country")  # 查找该层所有节点 country
print(node2)

for node in node2:
    if node.attrib["name"] == "日本":  # 找到属性名为日本的节点
        root.remove(node)    # 调用上该节点的父节点来删除
        break
tree.write("02.xml",encoding="utf-8")  # 执行完毕写回文件




dict1 = {}

for i in root:  # 遍历根节点的子节点 (一级节点)
    print("tag:{},attrib:{},text:{}".format(i.tag,i.attrib,i.text))
    value = []




    for j in i:  # 遍历一级节点的子节点(二级节点)
        print("tag:{},attrib:{},text:{}".format(j.tag,j.attrib,j.text))
        for k in j:
            print("tag:{},attrib:{},text:{}".format(k.tag,k.attrib,k.text))

        if j.text is None:
            value.append(j.attrib)
        else:
            value.append({j.tag:j.text})
    dict1[i.attrib["name"]] = value
print(dict1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值