Python XML自动化处理全攻略分享
作者:老胖闲聊
在当今的信息化时代,XML作为一种重要的数据交换格式,广泛应用于各种领域,Python作为一种功能强大的编程语言,也提供了丰富的库来支持对XML文档的操作,本章将介绍Python XML自动化处理全攻略,需要的朋友可以参考下
一、常用 XML 处理库简介
- xml.etree.ElementTree
- Python 标准库,轻量级,适合基础操作。
- lxml
- 第三方高性能库,支持 XPath、XSLT 和 Schema 验证。
- xml.dom / xml.sax
- 标准库实现,适合处理大型 XML 或事件驱动解析。
- 辅助工具库
xmltodict(XML ↔ 字典)、untangle(XML → Python 对象)等。
二、xml.etree.ElementTree 详解
1. 解析 XML
import xml.etree.ElementTree as ET
# 从字符串解析
root = ET.fromstring("<root><child>text</child></root>")
# 从文件解析
tree = ET.parse("file.xml")
root = tree.getroot()
2. 数据查询与修改
# 遍历子元素
for child in root:
print(child.tag, child.attrib)
# 查找元素
element = root.find("child")
element.text = "new_text" # 修改文本
element.set("attr", "value") # 修改属性
3. 生成与保存 XML
root = ET.Element("root")
child = ET.SubElement(root, "child", attrib={"key": "value"})
child.text = "content"
tree = ET.ElementTree(root)
tree.write("output.xml", encoding="utf-8", xml_declaration=True)
三、lxml 库高级操作
1. XPath 查询
from lxml import etree
tree = etree.parse("file.xml")
elements = tree.xpath("//book[price>20]/title/text()") # 查询价格>20的书名
2. XML Schema 验证
schema = etree.XMLSchema(etree.parse("schema.xsd"))
parser = etree.XMLParser(schema=schema)
try:
etree.parse("data.xml", parser)
except etree.XMLSchemaError as e:
print("验证失败:", e)
四、XML 与 Excel 互转
1. XML → Excel (XLSX)
from openpyxl import Workbook
import xml.etree.ElementTree as ET
tree = ET.parse("books.xml")
root = tree.getroot()
wb = Workbook()
ws = wb.active
ws.append(["书名", "作者", "价格"])
for book in root.findall("book"):
title = book.find("title").text
author = book.find("author").text
price = book.find("price").text
ws.append([title, author, price])
wb.save("books.xlsx")
2. Excel (XLSX) → XML
from openpyxl import load_workbook
import xml.etree.ElementTree as ET
def xlsx_to_xml(input_file, output_file):
wb = load_workbook(input_file)
ws = wb.active
root = ET.Element("bookstore")
headers = [cell.value.strip() for cell in ws[1]]
for row in ws.iter_rows(min_row=2, values_only=True):
book = ET.SubElement(root, "book")
for idx, value in enumerate(row):
tag = ET.SubElement(book, headers[idx])
tag.text = str(value)
ET.ElementTree(root).write(output_file, encoding="utf-8", xml_declaration=True)
xlsx_to_xml("books.xlsx", "books_from_excel.xml")
五、XML 与数据库交互
存储到 SQLite
import sqlite3
import xml.etree.ElementTree as ET
conn = sqlite3.connect("books.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS books (title TEXT, author TEXT, price REAL)")
tree = ET.parse("books.xml")
for book in tree.findall("book"):
title = book.find("title").text
author = book.find("author").text
price = float(book.find("price").text)
cursor.execute("INSERT INTO books VALUES (?, ?, ?)", (title, author, price))
conn.commit()
conn.close()
六、XML 与 JSON 互转
1. XML → JSON
import xmltodict
import json
with open("books.xml") as f:
xml_data = f.read()
data_dict = xmltodict.parse(xml_data)
with open("books.json", "w") as f:
json.dump(data_dict, f, indent=4, ensure_ascii=False)
2. JSON → XML
import xmltodict
import json
with open("books.json") as f:
json_data = json.load(f)
xml_data = xmltodict.unparse(json_data, pretty=True)
with open("books_from_json.xml", "w") as f:
f.write(xml_data)
七、性能优化与常见问题
1. 性能建议
- 小型数据: 使用
xml.etree.ElementTree。 - 大型数据: 使用
lxml的iterparse流式解析。 - 内存敏感场景: 使用
xml.sax事件驱动解析。
2. 常见问题解决
处理命名空间:
# lxml 示例
namespaces = {"ns": "http://example.com/ns"}
elements = root.xpath("//ns:book", namespaces=namespaces)
特殊字符处理:
element.text = ET.CDATA("<特殊字符>&")
依赖安装
pip install lxml openpyxl xmltodict
输入输出示例
- XML 文件 (
books.xml)
<bookstore>
<book>
<title>Python编程</title>
<author>John</author>
<price>50.0</price>
</book>
</bookstore>
- JSON 文件 (
books.json)
{
"bookstore": {
"book": {
"title": "Python编程",
"author": "John",
"price": "50.0"
}
}
}
通过本指南,可快速实现 XML 与其他格式的互转、存储及复杂查询操作,满足数据迁移、接口开发等多样化需求。
到此这篇关于Python XML自动化处理全攻略分享的文章就介绍到这了,更多相关Python XML自动化处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
