python如何处理xml,遇到非法格式的xml怎么办
Admin 2022-10-08 群英技术资讯 545 次浏览
参照官方文档,创建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')
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)对列表形式返回
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
bad.xml中找不到对应结束标记符时,内容如下:
<?xml version="1.0"?> <note> </Note>
因为区分大小写,所以</Note> 不能作为<note>的结束标记。
xml.parsers.expat.ExpatError: mismatched tag: line 3, column 2
bad.xml中属性值未包含在双引号(")之中时,遇到如下异常:
<?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
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了Python数据分析之 Matplotlib 饼图绘制,文章基于python的相关资料展开详细的饼图绘制,具有一定的参考价值,需要的小伙伴可以参考一下
这篇文章主要介绍了python数据结构之搜索讲解,搜索是指从元素集合中找到某个特定元素的算法过程。搜索过程通常返回 True 或 False, 分别表示元素是否存在,下面一起来了解文章的详细内容吧,希望对你有所帮助
python语言的3 x完全不向前兼容,导致我们在python2 x中可以正常使用的库,到了python3就用不了了 比如说mysqldb目前MySQLdb并不支持python3
这篇文章主要介绍了Django上传excel表格并将数据写入数据库,将文件上传到服务器指定路径,其实很简单,本文分三个步骤给大家详细介绍,需要的朋友可以参考下
这篇文章主要介绍了python中的脚本性能分析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008