python解析xml文件工具

本文介绍了Python中使用xml.etree.ElementTree模块解析和操作XML文件的基本方法,包括读取元素、修改XML文件,以及如何利用XPath进行更复杂的元素查找。通过示例展示了如何增加元素属性、删除元素和更新XML内容。

文章参考:xml.etree.ElementTree — The ElementTree XML API — Python 3.13.1 documentation

XML是一种广泛使用的格式,Python自身附带了一个完整的XML解析工具包,它支持SAX和DOM解析模式,此外还有一个名为ElementTree的包。这是特定于Python的专门用于解析和构造XML的API。除了基本的解析,开源领域还提供了额外的XML工具,例如XPath、Xquery、XSLT等。

官方建议:尚未熟悉DOM的用户应考虑使用xml.etree.ElementTree模块进行XML处理。鉴于我是个菜鸟,因此主要记录一下使用ElementTree进行XML文件解析的过程。xml.etree.ElementTree模块实现了一个简单而有效的API,用于解析和创建XML数据。

解析XML

使用下面的xml文件作为实例

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

使用下面的方法读取该文件:

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

此时的根结点是<data> </data>节点

>>> root.tag
'data'
>>> root.attrib
{}

对它的子节点进行迭代:

>>> for child in root:
...     print(child.tag, child.attrib)
...
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}

子项是嵌套的,我们可以通过索引访问特定的子节点:

>>> root[0][1].text
'2008'

读取元素

可以使用下面的函数读取根结点下面的所有子树(它的子节点,子节点的子节点等等)。

Element.iter():

>>> for neighbor in root.iter('neighbor'):
...     print(neighbor.attrib)
...
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Malaysia', 'direction': 'N'}
{'name': 'Costa Rica', 'direction': 'W'}
{'name': 'Colombia', 'direction': 'E'}

Element.findall() 仅查找带有标记的元素,这些元素是当前元素的直接子元素。

Element.find() 查找具有特定标记的第一个子元素。

Element.text 访问元素的文本内容。

Element.get()访问元素的属性。

>>> for country in root.findall('country'):
...     rank = country.find('rank').text
...     name = country.get('name')
...     print(name, rank)
...
Liechtenstein 1
Singapore 4
Panama 68

更复杂的指定要查找的元素可以使用XPath工具。

修改XML文件

ElementTree提供了一种构建XML文档并将其写入文件的简单方法。

ElementTree.write()  写入xml文件。

Element.text 读取或修改字段。

Element.set()添加或修改属性。

Element.append()添加新子元素。

Element.remove() 移除子节点。

假设我们对每个国家/地区的排名加一,并在rank元素中添加更新的属性:

>>> for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')
...
>>> tree.write('output.xml')

修改后的文件:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

假设我们要删除排名高于50的所有国家/地区:

>>> for country in root.findall('country'):
...     rank = int(country.find('rank').text)
...     if rank > 50:
...         root.remove(country)
...
>>> tree.write('output.xml')

处理结果:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
</data>

对xml文件的基本操作大致就是这些,如果想了解xml.etree.ElementTree中的全部函数和更高级的xml文件处理方法,请参考xml.etree.ElementTree — The ElementTree XML API — Python 3.13.1 documentation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值