[Python] Python操作XML

本教程介绍如何使用Python读取,修改XML文件。

 

范例XML文件内容(books.xml)

<bookstore>
<book category="fiction">
<title lang="chs">Lost Horzon</title>
<author>Mr. James Hilton</author>
<year>2015</year>
<price>66.0</price>
</book>

<book category="non-fiction">
<title lang="chs">My first half of life</title>
<author>Mr.Puyi</author>
<year>2015</year>
<price>72.0</price>
</book>

<book category="IT">
<title lang="chs">How to enter web programming</title>
<author paid="false">Mr.Leo Zhang</author>
<year>2025</year>
<price>142.0</price>
</book>
</bookstore>

 

导入xml.etree.ElementTree模块,别名ET,方便将来调用。

import xml.etree.ElementTree as ET

 

读取内容xml到xml.etree.ElementTree.ElementTree 对象(xml解析树)中。

tree = ET.ElementTree(file = 'books.xml')   #获取<xml.etree.ElementTree.ElementTree object at 0x7f1fe41c5430>   

 

获取ElementTree对象的根。

root = tree.getroot()    #获取<Element 'bookstore' at 0x7f1fdf3979f0>

 

访问xml文件的内容

对象的根获取后,可以从根作为访问的起点,通过root[0] 访问其第一个tag = book子元素,root[0][0]对应到 title, root[0][0].text 的值为Lost Horizon。

使用for循环遍历xml的内容。

for book in root:
    print('Title:',  book[0].text)
    print('Author:', book[1].text)
    print('year:',   book[2].text)
    print('Price:',  book[3].text)

###以下为运行结果###
Title: Lost Horzon
Author: Mr. James Hilton
year: 2015
Price: 66.0

Title: My first half of life Author: Mr.Puyi year: 2015 Price: 72.0

Title: How to enter web programming Author: Mr.Leo Zhang year: 2025 Price: 142

 

 

使用iter迭代器方法访问指定名称的子结点。下面范例得到一个tag='title'的标签集合,然后在其中进行遍历,得到所有的图书名字。

for title in root.iter(tag='title'):
    print(title.text)

###返回结果###
Lost Horzon
My first half of life
How to enter web programmin

如果元素的子元素还有同样名字的标签,我们以上方式搜索出来的数据可以不准确。

 

我们可以通过iterfind的方法按照路径获得指定的元素。

for title in root.iterfind('book/title'):
    print(title.text)

###返回结果###    
Lost Horzon
My first half of life
How to enter web programming

 

 

findall方法可以搜寻制定内容的标签或者路径。

#搜索路径
for title in root.iterfind('book/title'):
    print(title.text)

    
Lost Horzon
My first half of life
How to enter web programming

#搜索标签,只能搜索到当前位置的下一级的标签。比如在从root只能搜索到book。
从root[0] 可以搜索其包含的title, price, author, year.

for ele in root.findall('book'):
    print(ele.find('title').text)


Lost Horzon 
My first half of life
How to enter web programming

 

 

删除xml文件的内容

使用remove方法删除元素。

for book in root.findall('book'):
    price = book.find('price').text
    if float(price) <= 80:
        root.remove(book)

 

write()方法将修改后的数据保存

tree.write('asd.xml')  #参数是str类型就可以

 

 

更改xml的内容

直接对元素的tag和text进行赋值。对于attrib,使用字典的方式修改或者添加值。

root[0].attrib['New'] = 'true'
>>> root[0].attrib
{'category': 'Fid', 'New': 'true'}

 

 

添加xml的内容

使用xml.etree.ElementTree.ElementTree.SubElement(上层元素,新建元素名称)的方式创建。

 

>>> ET.SubElement(root, 'book')  #根下创建一对新的book标签

>>> ET.SubElement(root[3], 'title')  #新创建的book标签下,创建新的标签
>>> ET.SubElement(root[3], 'Author')
>>> ET.SubElement(root[3], 'Year')
>>> ET.SubElement(root[3], 'Price')

>>> root[3][0].text = 'Mastering Windows 2022'  #为新创建出来的标签赋值
>>> root[3][1].text = 'Bill Gates'
>>> root[3][2].text = '1998'
>>> root[3][3].text = '20.0'

>>> tree.write('asd.xml')

xml会多出来创建的内容。
<book><title>Mastering Windows 2022</title><Author>Bill Gates</Author><Year>1998</Year><Price>20.0</Price></book>

 

posted on 2022-03-31 21:02  LeoZhangJing  阅读(188)  评论(0编辑  收藏  举报

导航