Python?XML自動化處理全攻略分享
更新時間:2025年03月25日 08:28:09 作者:老胖閑聊
在當今的信息化時代,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("http://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)
七、性能優(yōu)化與常見問題
1. 性能建議
- 小型數據: 使用
xml.etree.ElementTree
。 - 大型數據: 使用
lxml
的iterparse
流式解析。 - 內存敏感場景: 使用
xml.sax
事件驅動解析。
2. 常見問題解決
處理命名空間:
# lxml 示例 namespaces = {"ns": "http://example.com/ns"} elements = root.xpath("http://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 與其他格式的互轉、存儲及復雜查詢操作,滿足數據遷移、接口開發(fā)等多樣化需求。
到此這篇關于Python XML自動化處理全攻略分享的文章就介紹到這了,更多相關Python XML自動化處理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
windows上徹底刪除jupyter notebook的實現
這篇文章主要介紹了windows上徹底刪除jupyter notebook的實現,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04Django admin管理工具TabularInline類用法詳解
這篇文章主要介紹了Django admin管理工具TabularInline類用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python SMTP發(fā)送郵件遇到的一些問題及解決辦法
今天小編就為大家分享一篇關于Python SMTP發(fā)送郵件遇到的一些問題及解決辦法,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10