Python使用lxml解析XML格式化数据

Python使用lxml解析XML格式化数据

  • [1. 效果图](#1. 效果图)
  • [2. 源代码](#2. 源代码)
  • 参考

方法一:无脑读取文件,遇到有关键词的行再去解析获取值

方法二:利用lxml等库,解析格式化数据,批量获取标签及其值

这篇博客介绍第2种办法,以菜鸟教程中的俩个xml文档为例进行解析;
https://www.runoob.com/try/xml/cd_catalog.xml
https://www.runoob.com/try/xml/books.xml

1. 效果图

cd_catalog.xml原始文件如下:

解析cd_catalog.xml后按顺序打印如下:

book.xml原始文件如下:

解析books.xml效果图如下:

2. 源代码

python 复制代码
# parseXml.py
# 解析cd_catalog.xml,book.xml

from xml.etree import ElementTree as ET


def readBookXml(file):
    # 直接读取xml文件,形成ElementTree结构
    tree = ET.parse(file)
    root = tree.getroot()  # 获取根元素
    for i, child in enumerate(root):  # 遍历子元素
        print(i, child.tag, child.text, child.attrib)  # 输出子元素的标签和属性值
        for j in range(len(child)):
            print('\t', j, child[j].tag, child[j].text, child[j].attrib)  # 输出子元素中的标签及属性值

    # 获取XML文档的根元素
    root = tree.getroot()

    # 查找具有指定标签的第一个子元素
    element = root.find('book')

    # 查找具有指定标签的所有子元素
    books = root.findall('book')

    print(len(books))
    for i, book in enumerate(books):
        print(i, book.tag, book.text, book.attrib)  # 输出子元素的标签和属性值
        for j in range(len(book)):
            print('\t', j, book[j].tag, book[j].text, book[j].attrib)  # 输出子元素中的标签及属性值


def readCatalogXml(file):
    # 直接读取xml文件,形成ElementTree结构
    tree = ET.parse(file)
    root = tree.getroot()  # 获取根元素
    for i, child in enumerate(root):  # 遍历子元素
        print(i, child.tag, child.text, child.attrib)  # 输出子元素的标签和属性值
        for j in range(len(child)):
            print('\t', j, child[j].tag, child[j].text, child[j].attrib)  # 输出子元素中的标签及属性值

    # 获取XML文档的根元素
    root = tree.getroot()

    # 查找具有指定标签的第一个子元素
    element = root.find('CD')

    # 查找具有指定标签的所有子元素
    books = root.findall('CD')

    print(len(books))
    for i, book in enumerate(books):
        print(i, book.tag)  # 输出子元素的标签
        for j in range(len(book)):
            print('\t', j, book[j].tag, book[j].text)  # 输出子元素中的标签及属性值


file = 'test/books.xml'
readBookXml(file)

file = 'test/cd_catalog.xml'
readCatalogXml(file)

参考

相关推荐
灰太狼爱红太狼3 小时前
2025睿抗机器人大赛智能侦查赛道省赛全流程
人工智能·python·目标检测·ubuntu·机器人
轻竹办公PPT3 小时前
2026 年工作计划怎么汇报?AI 自动生成 PPT 方案
python·powerpoint
鲜卑大帝3 小时前
十五五规划重点领域分析报告十五五规划聚焦高质量发展与战略突破,涵盖经济、科技、社会、生态等多个领域,是指导未来五年国家发展的重要纲领。
python
yousuotu3 小时前
基于Python的亚马逊销售数据集探索性数据分析
开发语言·python·数据分析
曲幽3 小时前
掌握Fetch与Flask交互:让前端表单提交更优雅的动态之道
python·flask·json·web·post·fetch·response
-Excalibur-3 小时前
ARP RIP OSPF BGP DHCP以及其他计算机网络当中的通信过程和广播帧单播帧的整理
c语言·网络·python·学习·tcp/ip·算法·智能路由器
小白学大数据3 小时前
Python 网络爬虫:Scrapy 解析汽车之家报价与评测
开发语言·爬虫·python·scrapy
-Excalibur-4 小时前
关于计算机网络当中的各种计时器
java·c语言·网络·c++·笔记·python·计算机网络
太一吾鱼水4 小时前
matplotlib的imshow显示图片颜色正常,用cv2保存颜色不对
python
傻啦嘿哟4 小时前
Python实现Excel数据自动化处理:从繁琐操作到智能流程的蜕变
python·自动化·excel