Python标准库ElementTree处理XML详解与异常排查

夏知夏
夏知夏
发布时间:2026-10-15 | 2人浏览过
原创

本文详解Python标准库ElementTree处理XML文件的方法,包括ElementTree对象的创建、Element对象的常用属性与操作方法。重点分析解析非法XML时常见的ExpatError异常,如no element found、mismatched tag及not well-formed错误,并提供对应的代码示例与排查建议。

1. 示例用法

参考官方文档,我们首先构建一个名为country_data.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>

接下来使用以下代码读取该数据并进行打印输出:

from xml.etree.ElementTree 
data = ElementTree.ElementTree(file='country_data.xml')
country_list = data.findall('country')   #找到所有名为‘country'的tag,返回一个Element对象列表。
for country in country_list:
    name = country.attrib.get('name', '') 
    print name, ' ', 
    for item in country:
        if item.tag == 'neighbor':
            name = item.attrib.get('name', '') 
            direction = item.attrib.get('direction', '') 
            print '{0} ({1})'.format(name, direction), ' ',
        else:
            print item.text, ' ',
    print ''

其中

data = ElementTree.ElementTree(file='country_data.xml')

上述代码旨在获取一个ElementTree对象。此外,你也可以通过以下方式实现:

tree = ElementTree.parse('country_data.xml')

Element对象具备以下关键属性和操作方法:

elem.tag这个Element对象的名字(tag)
elem.text文档内容
elem.attrib属性值字典
elem.tail与属性一起存储的其他数据

elem[n] 用于返回elem的第n个子元素

elem[n] = new_elem 用于将elem的第n个子元素替换为新的元素new_elem

del elem[n] 用于删除指定的子元素

len(elem) 用于获取子元素的总数量

elem.find(path)

elem.getchildren() 按文档顺序返回所有子元素

elem.items() 将所有元素的属性值以(name, value)对的形式返回

遇到非法格式的xml

ExpatError: no element found

当bad.xml为空文档时,其内容如下:

<?xml version="1.0"?>

执行以下Python代码时,会触发xml.parser.expat.ExpatError异常:

import xml.etree.ElementTree as ET
ET.parse('bad.xml')

xml.parsers.expat.ExpatError: no element found: line 3, column 0

ExpatError: mismatched tag

当bad.xml中找不到对应的结束标记符时,其内容如下:

<?xml version="1.0"?>
<note>
</Note>

由于XML标签区分大小写,因此</Note>无法作为<note>的结束标记。

xml.parsers.expat.ExpatError: mismatched tag: line 3, column 2

ExpatError: not well-formed(invalid token)

当bad.xml中的属性值未使用双引号(&quot;)包裹时,会触发如下异常:

<?xml version="1.0"?>
<note id=hello>
</note>

若bad.xml中包含非法符号,例如在"if salary < 1000 then"语句中的‘<'符号,情况如下:

<?xml version="1.0"?>
<note id="hello">
if salary < 1000 then
</note

xml.parsers.expat.ExpatError: not well-formed (invalid token): line 2, column 9

以上就是python标准库ElementTree处理xml的详细内容,更多关于python ElementTree处理xml的资料请关注本站其它相关文章!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表