如何用Python解析XML并存入SQLite数据库

4次阅读

python解析 xml 存入 sqlite 需三步:先用 xml.etree.ElementTree 分析结构并提取字段(区分。get() 取属性与。text 取文本),再转为字典列表;然后用 sqlite 3 建表(注意字段类型匹配);最后 executemany() 批量插入,兼顾安全与性能。

如何用 Python 解析 XML 并存入 SQLite 数据库

用 Python 解析 XML 并存入 SQLite数据库 ,核心是三步:读取 XML、提取数据、插入 SQLite。关键在于结构化处理——XML 格式多变,需先理清标签层级和字段映射关系,再用 标准库 xml.etree.ElementTree)安全解析,避免第三方依赖;SQLite 用sqlite3 原生支持,无需额外安装。

1. 分析 XML 结构,明确要存的字段

比如有如下简化 XML(books.xml):

<library>   <book id="1">     <title>python 编程</title>     <author> 张三 </author>     <price>59.9</price>   </book>   <book id="2">     <title> 数据结构 </title>     <author> 李四 </author>     <price>45.5</price>   </book> </library>

目标字段是:id(属性)、titleauthorprice。注意 idbook标签上,其余是子元素内容——解析时需区分.get()(取属性)和.text(取文本)。

2. 用 ElementTree 解析 XML,转为 Python 字典列表

不建议直接逐节点拼 SQL,先统一转成结构化数据更安全、易调试:

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

  • ET.parse() 加载文件,或 ET.fromstring() 加载 字符串
  • .findall("book") 定位所有记录节点
  • 对每个 book,用.get("id") 取属性,.find("title").text等取子元素值
  • try/except 防缺失字段(如某本书没<price></price>),设默认值或跳过

示例代码片段:

import xml.etree.ElementTree as ET  tree = ET.parse("books.xml") root = tree.getroot()  books = [] for book in root.findall("book"):     books.append({"id": book.get("id"),         "title": book.find("title").text if book.find("title") is not None else None,         "author": book.find("author").text if book.find("author") is not None else None,         "price": Float(book.find("price").text) if book.find("price") is not None else None,     })

3. 创建 SQLite 表并批量插入

表结构要匹配字段类型:id可设 TEXT 或 Integer(若 XML 中全是数字),price 用 REAL,title/author用 TEXT:

  • sqlite3.connect() 连数据库(文件不存在会自动创建)
  • cursor.execute()建表,注意加 IF NOT EXISTS 避免重复报错
  • executemany() 批量插入,比 循环 execute() 快得多,且自动处理sql 注入(参数化)
  • 别忘了 conn.commit()conn.close()

接上例:

import sqlite3  conn = sqlite3.connect("library.db") cursor = conn.cursor()  cursor.execute("""     CREATE TABLE IF NOT EXISTS books (         id TEXT PRIMARY KEY,         title TEXT,         author TEXT,         price REAL) """)  cursor.executemany("INSERT OR REPLACE INTO books (id, title, author, price) VALUES (?, ?, ?, ?)",     [(b["id"], b["title"], b["author"], b["price"]) for b in books] )  conn.commit() conn.close()

4. 小心常见坑

编码 问题 :XML 文件含中文时,确保用ET.parse("books.xml", parser=ET.XMLParser(encoding="utf-8")) 显式指定 编码
空值与类型 :XML 中<price></price> 或空白标签会导致 .textNone,转换 float(None) 会报错,务必提前判断。
特殊字符 :ElementTree 能自动处理& 等实体,不用手动解码。<br><strong><a style="color:#f60; text-decoration:underline;" title="大数据 " href="https://www.php.cn/zt/16141.html" target="_blank"> 大数据 </a> 量 </strong>:若 XML 超大(百 MB 以上),改用 <code>iterparse() 边读边处理,避免内存爆满。

站长
版权声明:本站原创文章,由 站长 2025-12-17发表,共计2579字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
1a44ec70fbfb7ca70432d56d3e5ef742
text=ZqhQzanResources