Python?XML自動(dòng)化處理全攻略分享
一、常用 XML 處理庫(kù)簡(jiǎn)介
- xml.etree.ElementTree
- Python 標(biāo)準(zhǔn)庫(kù),輕量級(jí),適合基礎(chǔ)操作。
- lxml
- 第三方高性能庫(kù),支持 XPath、XSLT 和 Schema 驗(yàn)證。
- xml.dom / xml.sax
- 標(biāo)準(zhǔn)庫(kù)實(shí)現(xiàn),適合處理大型 XML 或事件驅(qū)動(dòng)解析。
- 輔助工具庫(kù)
xmltodict
(XML ↔ 字典)、untangle
(XML → Python 對(duì)象)等。
二、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. 數(shù)據(jù)查詢與修改
# 遍歷子元素 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 庫(kù)高級(jí)操作
1. XPath 查詢
from lxml import etree tree = etree.parse("file.xml") elements = tree.xpath("http://book[price>20]/title/text()") # 查詢價(jià)格>20的書名
2. XML Schema 驗(yàn)證
schema = etree.XMLSchema(etree.parse("schema.xsd")) parser = etree.XMLParser(schema=schema) try: etree.parse("data.xml", parser) except etree.XMLSchemaError as e: print("驗(yàn)證失敗:", e)
四、XML 與 Excel 互轉(zhuǎn)
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(["書名", "作者", "價(jià)格"]) 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 與數(shù)據(jù)庫(kù)交互
存儲(chǔ)到 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 互轉(zhuǎn)
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)化與常見問(wèn)題
1. 性能建議
- 小型數(shù)據(jù): 使用
xml.etree.ElementTree
。 - 大型數(shù)據(jù): 使用
lxml
的iterparse
流式解析。 - 內(nèi)存敏感場(chǎng)景: 使用
xml.sax
事件驅(qū)動(dòng)解析。
2. 常見問(wèn)題解決
處理命名空間:
# 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" } } }
通過(guò)本指南,可快速實(shí)現(xiàn) XML 與其他格式的互轉(zhuǎn)、存儲(chǔ)及復(fù)雜查詢操作,滿足數(shù)據(jù)遷移、接口開發(fā)等多樣化需求。
到此這篇關(guān)于Python XML自動(dòng)化處理全攻略分享的文章就介紹到這了,更多相關(guān)Python XML自動(dòng)化處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
windows上徹底刪除jupyter notebook的實(shí)現(xiàn)
這篇文章主要介紹了windows上徹底刪除jupyter notebook的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04淺談Python Opencv中g(shù)amma變換的使用詳解
下面小編就為大家分享一篇淺談Python Opencv中g(shù)amma變換的使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Django項(xiàng)目實(shí)戰(zhàn)之用戶頭像上傳與訪問(wèn)的示例
這篇文章主要介紹了Django項(xiàng)目實(shí)戰(zhàn)之用戶頭像上傳與訪問(wèn)的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Django admin管理工具TabularInline類用法詳解
這篇文章主要介紹了Django admin管理工具TabularInline類用法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05python實(shí)現(xiàn)處理Excel表格超詳細(xì)系列
這篇文章主要介紹了python實(shí)現(xiàn)處理Excel表格超詳細(xì)系列,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08Django數(shù)據(jù)結(jié)果集序列化并展示實(shí)現(xiàn)過(guò)程
這篇文章主要介紹了Django數(shù)據(jù)結(jié)果集序列化并展示實(shí)現(xiàn)過(guò)程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04Python SMTP發(fā)送郵件遇到的一些問(wèn)題及解決辦法
今天小編就為大家分享一篇關(guān)于Python SMTP發(fā)送郵件遇到的一些問(wèn)題及解決辦法,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10