Python 如何基于XML文件创建python对象
XML(可扩展标记语言)是一种用于结构化、存储和传输数据的标记语言。在某些情况下,我们需要使用Python语言读取/写入XML数据。
通过使用untangle库,我们可以基于XML文件创建Python对象。untangle是一个小型的Python库,它将XML文档转换为Python对象。
untangle具有非常简单的API。我们只需调用parse()函数即可获得一个Python对象。
语法
untangle.parse(filename,**parser_features)
参数
- filename: 可以是一个XML字符串,一个XML文件名或一个URL
-
parser_features: 额外的参数被视为要传递给parser.setFeature()的特征值。
返回值
该函数对其进行解析并返回一个表示给定XML文档的Python对象。
安装Untangle库
要使用untangle.parse()函数,我们首先需要安装该库。通过使用下面的命令,我们可以安装该库。
使用pip安装
pip install untangle
使用Anaconda进行安装
conda install -c conda-forge untangle
示例1
让我们拿一个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对象。使用untangle模块将XML文件(file.xml)转换为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'
示例2
让我们来看一个真实的例子,来自于Planet Python的RSS源,然后提取博客标题及其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
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
Functions in Python are Like a Coffee Machine
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
Select Row From a Dataframe in Python
PyCoder's Weekly: Issue #542 (Sept. 13, 2022)
https://pycoders.com/issues/542 ……………………………
在这个例子中,我们将XML数据的url发送给解析函数,然后使用for循环迭代元素。