首页 > 代码库 > python处理xml文件
python处理xml文件
参考:https://docs.python.org/2/library/xml.etree.elementtree.html
例子:
<?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>
1、解析xml文件
>>> os.getcwd() ‘D:\\workspace\\testpython‘ >>> import xml.etree.ElementTree as ET >>> tree = ET.parse(‘test.xml‘) >>> root = tree.getroot() >>> print root <Element ‘data‘ at 0x1d2a8b0> >>> print tree <xml.etree.ElementTree.ElementTree object at 0x01D2A9D0> >>> 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].text ‘\n ‘ >>> root[0][1].text ‘2008‘ >>> root[1][3].text >>> root[1][2].text ‘59900‘
2、查找元素
>>> #查询元素 >>> for neighbor in root.iter(‘neighbor‘): print neighbor.attrib {‘direction‘: ‘E‘, ‘name‘: ‘Austria‘} {‘direction‘: ‘W‘, ‘name‘: ‘Switzerland‘} {‘direction‘: ‘N‘, ‘name‘: ‘Malaysia‘} {‘direction‘: ‘W‘, ‘name‘: ‘Costa Rica‘} {‘direction‘: ‘E‘, ‘name‘: ‘Colombia‘} >>> root.iter(‘neighbor‘) <generator object iter at 0x01D3CF30> >>> root.findall(‘country‘) [<Element ‘country‘ at 0x1d2aa90>, <Element ‘country‘ at 0x1d2ad30>, <Element ‘country‘ at 0x1d2af10>] >>> for country in root.findall(‘country‘): #element.findall()查询当前元素的子元素 rank=country.find(‘rank‘).text #element.find()查询指定标签的第一个子元素,element.text获取元素的内容 name=country.get(‘name‘) #element.get()获取元素的属性值 print name,rank Liechtenstein 1 Singapore 4 Panama 68
3、修改xml文件
python处理xml文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。