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)

参考

相关推荐
旦莫8 分钟前
Python 教程:我们可以给 Python 文件起中文名吗?
开发语言·python
豌豆花下猫25 分钟前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
小杨40429 分钟前
python入门系列二十(peewee)
人工智能·python·pycharm
弧襪29 分钟前
FlaskRestfulAPI接口的初步认识
python·flaskrestfulapi
船长@Quant31 分钟前
文档构建:Sphinx全面使用指南 — 进阶篇
python·markdown·sphinx·文档构建
cloudy49134 分钟前
强化学习:历史基金净产值,学习最大化长期收益
python·强化学习
Bruce_Liuxiaowei1 小时前
使用Python脚本在Mac上彻底清除Chrome浏览历史:开发实战与隐私保护指南
chrome·python·macos
ruyingcai6666661 小时前
用python进行OCR识别
开发语言·python·ocr
Niuguangshuo1 小时前
Python设计模式:MVC模式
python·设计模式·mvc
TOMGRIL1 小时前
文件的读取操作
python