XML(可扩展性标记语言)是一种很是经常使用的文件类型,主要用于存储和传输数据。在编程中,对XML的操做也很是常见。html
本文根据python库文档中的xml.etree.ElementTree类来进行介绍XML的解析:https://docs.python.org/3.5/library/xml.etree.elementtree.html python
BTW,xml.etree.cElementTree模块从3.3之后就被弃用了.编程
首先,来看一下XML所包含的元素类型app
1. 标签 <tag>学习
2. 属性 <tag name="attribute">spa
3. 数据 <data>1<data>code
例如 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>
#从变量读取,参数为XML段,返回的是一个根Element对象 root = ET.fromstring(country_data_as_string) #从xml文件中读取,用getroot获取根节点,根节点也是Element对象 tree = ET.parse('file.xml') root = tree.getroot()
tag = element.tag attrib = element.attrib value = element.text
#打印根节点的标签和属性,获取 for child in root: print(child.tag, child.attrib)
#打印根节点中全部的neighbor对象的name属性 for neighbor in root.iter('neighbor'): print(neighbor.attrib['name'])
#findall只能用来查找直接子元素,不能用来查找rank,neighbor等element for country in root.findall('country'): rank = country.find('rank').text name = country.find('rank').text neig = country.find('neighbor').attrib print(rank, name,neig)
#返回第一个tag为country的element,如没有,返回None firstCountry = root.find("country") print(firstCountry)
__author__ = 'xua' import xml.etree.ElementTree as ET #建立根节点 a = ET.Element("root") #建立子节点,并添加属性 b = ET.SubElement(a,"sub1") b.attrib = {"name":"name attribute"} #建立子节点,并添加数据 c = ET.SubElement(a,"sub2") c.text = "test" #建立elementtree对象,写文件 tree = ET.ElementTree(a) tree.write("test.xml")
建立的新文件内容为:<root><sub1 name="name attribute" /><sub2>test</sub2></root>htm
#读取待修改文件 updateTree = ET.parse("test.xml") root = updateTree.getroot() #建立新节点并添加为root的子节点 newEle = ET.Element("NewElement") newEle.attrib = {"name":"NewElement","age":"20"} newEle.text = "This is a new element" root.append(newEle) #修改sub1的name属性 sub1 = root.find("sub1") sub1.set("name","New Name") #修改sub2的数据值 sub2 = root.find("sub2") sub2.text = "New Value" #写回原文件 updateTree.write("test.xml")
更新完的文件为:<root><sub1 name="New Name" /><sub2>New Value</sub2><NewElement age="20" name="NewElement">This is a new element</NewElement></root>对象
XML的操做比较常见,固然也有不少第三方的库能够使用,所须要作的操做无非就是经常使用的读写xml文件、元素节点的增删改查,你们还能够在python官方文档上学习更多的操做。
https://docs.python.org/3.5/library/xml.etree.elementtree.html