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)

参考

相关推荐
大模型铲屎官32 分钟前
【Python-Day 14】玩转Python字典(上篇):从零开始学习创建、访问与操作
开发语言·人工智能·pytorch·python·深度学习·大模型·字典
yunvwugua__34 分钟前
Python训练营打卡 Day27
开发语言·python
Stara05112 小时前
基于多头自注意力机制(MHSA)增强的YOLOv11主干网络—面向高精度目标检测的结构创新与性能优化
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·yolov11
那雨倾城3 小时前
使用 OpenCV 将图像中标记特定颜色区域
人工智能·python·opencv·计算机视觉·视觉检测
LuckyTHP5 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
mahuifa7 小时前
(7)python开发经验
python·qt·pyside6·开发经验
学地理的小胖砸8 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
安迪小宝8 小时前
6 任务路由与负载均衡
运维·python·celery
Blossom.1188 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
lisw058 小时前
Python高级进阶:Vim与Vi使用指南
python·vim·excel