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)

参考

相关推荐
代码欢乐豆36 分钟前
scikit-learn零基础配置(含python、anaconda)
python·机器学习·scikit-learn
Java水解1 小时前
Python数据库操作:SQLAlchemy ORM指南
python
悠哉悠哉愿意1 小时前
【数学建模学习笔记】无监督聚类模型:分层聚类
笔记·python·学习·数学建模
eleqi1 小时前
Python+DRVT 从外部调用 Revit:批量创建门
python·系统集成·bim·revit·drvt·自动生产流水线
先做个垃圾出来………1 小时前
PyTorch 模型文件介绍
人工智能·pytorch·python
浅醉樱花雨1 小时前
vosk语音识别实战
人工智能·python·语音识别·asr·vosk
再努力"亿"点点2 小时前
爬取m3u8视频完整教程
开发语言·python
悟能不能悟2 小时前
if __name__=‘__main__‘的用处
python
Source.Liu2 小时前
【Python基础】 15 Rust 与 Python 基本类型对比笔记
笔记·python·rust
前端世界2 小时前
Python 正则表达式实战:用 Match 对象轻松解析拼接数据流
python·正则表达式·php