Python使用DOM解析XML文件

Python使用DOM解析XML文件

使用DOM解析xml文件操作简单,很适合我(Yes~!)
这里还有 SAX解析XML文件 方式,但相对复杂一些。

import xml.dom.minidom

# 使用DOM解析XML文件
domTree = xml.dom.minidom.parse("large_intestine.xml")
collection = domTree.documentElement
if collection.hasAttribute("year"):
    print("This a breakfast menu")
    print(f"年份:{collection.getAttribute('year')}")
    print()
foods = collection.getElementsByTagName("food")
for food in foods:
    name = food.getElementsByTagName("name")[0]
    print(f"name: {name.childNodes[0].data}")
    price = food.getElementsByTagName("price")[0]
    print(f"price: {price.childNodes[0].data}")
    description = food.getElementsByTagName("description")[0]
    print(f"description: {description.childNodes[0].data}")
    calories = food.getElementsByTagName("calories")[0]
    print(f"calories: {calories.childNodes[0].data}")
    print("------------------------")

所解析的xml文件同样是上一次使用的large_intestine.xml

<breakfast_menu year="2023">
    <food>
        <name>Belgian Waffles</name>
        <price>$6.3</price>
        <description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
        <calories>650</calories>
    </food>
    <food>
        <name>九转大肠</name>
        <price>$9.9</price>
        <description>我去除了大部分的腥味,但在清洗的过程中故意保留了一部分</description>
        <calories>999</calories>
    </food>
</breakfast_menu>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值