如何基於 XML 檔案建立 Python 物件?
XML(可擴充套件標記語言)是一種用於結構化、儲存和在系統之間傳輸資料的標記語言。在某些情況下,我們需要使用 Python 語言讀取/寫入 XML 資料。
透過使用 untangle 庫,我們可以基於 XML 檔案建立 Python 物件。Untangle 是一個小型 Python 庫,它將 XML 文件轉換為 Python 物件。
Untangle 具有非常簡單的 API。我們只需要呼叫 parse() 函式即可獲取 Python 物件。
語法
untangle.parse(filename, **parser_features)
引數
檔名:可以是 XML 字串、XML 檔名或 URL
**解析器特性:傳遞給 parser.setFeature() 的作為特性值處理的額外引數。
返回值
該函式對其進行解析並返回一個 Python 物件,該物件表示給定的 XML 文件。
安裝 Untangle 庫
要使用 untangle.parse() 函式,我們需要先安裝該庫。透過使用以下命令,我們可以安裝該庫。
使用 pip 安裝
pip install untangle
使用 anaconda 安裝
conda install -c conda-forge untangle
示例
讓我們以一個 XML 字串為例,並建立 Python 物件。
xml = """<main>
<object1 attr="name">content</object1>
<object1 attr="foo">contenbar</object1>
<test>me</test>
</main>"""
import untangle
doc = untangle.parse(xml) # reading XML string data
obj1 = doc.main.object1
print(obj1)
print('-------------')
obj2 = doc.main.test
print(obj2)
輸出
[Element(name = object1, attributes = {'attr': 'name'}, cdata = content), Element(name = object1, attributes = {'attr': 'foo'}, cdata = contenbar)]
-------------
Element <test> with attributes {}, children [] and cdata me
使用 untangle 庫,我們已成功將 XML 資料轉換為 Python 物件。以一個 XML 檔案 (file.xml) 為例,並使用 untangle 模組將其轉換為 Python 物件。XML 檔案中的資料如下所示
<?xml version="1.0"?>
<root>
<child name="child1"/>
</root>
現在,讀取上述 xml 檔案以建立一個 python 物件。
import untangle
obj = untangle.parse('path/to/file.xml')
obj.root.child['name']
在為 XML 資料建立 Python 物件後,我們可以像上面一樣獲取子元素。
輸出
'child1'
示例
讓我們來看一個現實世界的例子,從 Planet Python 的 RSS Feed 中提取文章標題及其 URL。
import untangle
xml = "https://planetpython.org/rss20.xml"
obj = untangle.parse(xml)
for item in obj.rss.channel.item:
title = item.title.cdata
link = item.link.cdata
print(title)
print(' ', link)
輸出
IslandT: Python Tutorial -- Chapter 4
https://islandtropicaman.com/wp/2022/09/15/python-tutorial-chapter-4/
Tryton News: Debian integration packages for Tryton
https://discuss.tryton.org/t/debian-integration-packages-for-tryton/5531
Python Does What?!: Mock Everything
https://www.pythondoeswhat.com/2022/09/mock-everything.html
The Python Coding Blog: Functions in Python are Like a Coffee Machine
https://thepythoncodingbook.com/2022/09/14/functions-in-python-are-like-coffee-machines/
Real Python: How to Replace a String in Python
https://realpython.com/replace-string-python/
Python for Beginners: Select Row From a Dataframe in Python
https://www.pythonforbeginners.com/basics/select-row-from-a-dataframe-in-python
PyCoder's Weekly: Issue #542 (Sept. 13, 2022)
https://pycoders.com/issues/542 ……………………………
在此示例中,我們將 XML 資料的 URL 傳送到 parse 函式,然後使用 for 迴圈迭代元素。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP