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>