Python XML自动化处理全攻略分享

 更新时间:2025年03月25日 08:28:09   作者:老胖闲聊  
在当今的信息化时代,XML作为一种重要的数据交换格式,广泛应用于各种领域,Python作为一种功能强大的编程语言,也提供了丰富的库来支持对XML文档的操作,本章将介绍Python XML自动化处理全攻略,需要的朋友可以参考下

一、常用 XML 处理库简介

  1. xml.etree.ElementTree
    • Python 标准库,轻量级,适合基础操作。
  2. lxml
    • 第三方高性能库,支持 XPath、XSLT 和 Schema 验证。
  3. xml.dom / xml.sax
    • 标准库实现,适合处理大型 XML 或事件驱动解析。
  4. 辅助工具库
    • 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自动化处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • windows上彻底删除jupyter notebook的实现

    windows上彻底删除jupyter notebook的实现

    这篇文章主要介绍了windows上彻底删除jupyter notebook的实现,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • 浅谈Python Opencv中gamma变换的使用详解

    浅谈Python Opencv中gamma变换的使用详解

    下面小编就为大家分享一篇浅谈Python Opencv中gamma变换的使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-04-04
  • Django项目实战之用户头像上传与访问的示例

    Django项目实战之用户头像上传与访问的示例

    这篇文章主要介绍了Django项目实战之用户头像上传与访问的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • 详解Python 中的命名空间、变量和范围

    详解Python 中的命名空间、变量和范围

    Python 是一种动态类型语言,在程序执行期间,变量名可以绑定到不同的值和类型,这篇文章主要介绍了Python 中的命名空间、变量和范围,需要的朋友可以参考下
    2022-09-09
  • Django admin管理工具TabularInline类用法详解

    Django admin管理工具TabularInline类用法详解

    这篇文章主要介绍了Django admin管理工具TabularInline类用法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • python实现处理Excel表格超详细系列

    python实现处理Excel表格超详细系列

    这篇文章主要介绍了python实现处理Excel表格超详细系列,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-08-08
  • Django数据结果集序列化并展示实现过程

    Django数据结果集序列化并展示实现过程

    这篇文章主要介绍了Django数据结果集序列化并展示实现过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • python matplotlib库直方图绘制详解

    python matplotlib库直方图绘制详解

    这篇文章主要介绍了python matplotlib库直方图绘制详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • Python中的复制、浅拷贝与深拷贝解读

    Python中的复制、浅拷贝与深拷贝解读

    这篇文章主要介绍了Python中的复制、浅拷贝与深拷贝解读,对于可变对象,赋值是最简单省事的,如b=a,意思是直接使得a指向b代表的对象,两者id一样,指向同一个对象,一个修改,另一个也随之变化,需要的朋友可以参考下
    2023-11-11
  • Python SMTP发送邮件遇到的一些问题及解决办法

    Python SMTP发送邮件遇到的一些问题及解决办法

    今天小编就为大家分享一篇关于Python SMTP发送邮件遇到的一些问题及解决办法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10

最新评论