Python如何从ZIP压缩包中直接读取XML文件

4次阅读

python可直接从ZIP读取xml无需解压,用zipfile.ZipFile配合xml.etree.ElementTree或lxml解析;需注意路径大小写、编码(如bom/GBK)及异常处理,支持批量读取与XPath查询。

Python如何从ZIP压缩包中直接读取XML文件

Python可以直接从ZIP压缩包中读取XML文件,无需先解压到磁盘——关键在于用zipfile.ZipFile打开ZIP,再用.open()获取文件对象,最后交给xml.etree.ElementTree(或lxml)解析。

使用标准库 zipfile + xml.etree.ElementTree

这是最轻量、无需额外安装的方式,适合结构清晰、编码明确的XML文件:

  • 确保ZIP内XML文件路径准确(区分大小写,注意子目录)
  • .open()返回的是类似文件的对象,可直接传给ET.parse()
  • 若XML含BOM或编码声明不一致,建议用ET.fromstring()配合.read().decode()手动处理

示例代码:

import zipfile import xml.etree.ElementTree as ET 

with zipfile.ZipFile("data.zip") as z: with z.open("folder/config.xml") as f: # 注意路径是ZIP内的相对路径 tree = ET.parse(f) root = tree.getroot() print(root.tag)

处理编码问题(如UTF-8 with BOM或GBK)

当XML声明为,或文件含BOM时,ET.parse()可能报错。此时应先读取字节流,再解码:

立即学习Python免费学习笔记(深入)”;

  • f.read()获取原始bytes
  • 按实际编码解码为字符串(可用chardet自动检测,或根据业务约定硬编码)
  • ET.fromstring()解析字符串

示例:

import zipfile import xml.etree.ElementTree as ET 

with zipfile.ZipFile("data.zip") as z: with z.open("doc.xml") as f: content = f.read() # bytes

假设已知是GBK编码

    xml_str = content.decode("gbk")     root = ET.fromstring(xml_str)

用 lxml 提升解析能力与容错性

如果XML格式不规范(如标签未闭合、有html式混用)、需要XPath、命名空间或更好性能,推荐用lxml

  • lxml.etree.parse()支持从文件对象直接解析,也兼容编码参数
  • 对乱码、缺失声明、嵌套错误更宽容
  • 需先安装:pip install lxml

示例:

from lxml import etree import zipfile 

with zipfile.ZipFile("archive.zip") as z: with z.open("report.xml") as f: tree = etree.parse(f, parser=etree.XMLParser(recover=True)) root = tree.getroot()

支持XPath

    items = root.xpath("//item[@status='active']")

批量读取ZIP中多个XML文件

利用z.namelist()筛选所有.xml文件,再逐个处理:

  • pathlib.PurePath判断后缀更可靠(避免.XML.Xml被忽略)
  • 异常需捕获(如某XML损坏),避免中断整个流程
  • 可结合生成器节省内存

示例:

import zipfile import xml.etree.ElementTree as ET from pathlib import PurePath 

def iter_xml_from_zip(zip_path): with zipfile.ZipFile(zip_path) as z: for name in z.namelist(): if PurePath(name).suffix.lower() == ".xml": try: with z.open(name) as f: yield name, ET.parse(f).getroot() except Exception as e: print(f"跳过 {name}:{e}")

for filename, root in iter_xml_from_zip("batch.zip"): print(f"{filename} → {root.tag}")

text=ZqhQzanResources