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)

参考

相关推荐
Yan-英杰36 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779132 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥3 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
小喵要摸鱼7 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn7 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML7 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover17 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
mengyoufengyu8 小时前
算法12-贪心算法
python·算法·贪心算法
T_Y99438 小时前
pythonrsa加密与sha256加密
python