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>
import xml.etree.ElementTree as ET
tree = ET.parse('xz.xml') #打开文件
root = tree.getroot()
print(root.tag)
#遍历文档
for child in root:
print(child.tag,child.attrib)
for i in child:
print(i.tag,i.text)
#遍历year节点
for node in root.iter('year'):
print(node.tag,node.text)
---------------------------------------------------------------------------
import xml.etree.ElementTree as ET
tree = ET.parse('xz.xml') #打开文件
root = tree.getroot() #seek(0)
#修改
for node in root.iter('year'):
new_year = int(node.text) + 10
node.text = str(new_year)
node.set('newcoding','yes')
tree.write('test.xml')
#删除
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('outtest.xml')
自建xml
import xml.etree.ElementTree as ET
root = ET.Element('nameroot')
people = ET.SubElement(root,'people',attrib = {'enrolled':'yes'})
name = ET.SubElement(people,'name')
name.text = 'Bob'
age = ET.SubElement(people,'age',attrib={'enrooled':'no'})
gender = ET.SubElement(people,'gender')
gender.text = 'male'
people = ET.SubElement(root,'people',attrib = {'enrolled':'yes'})
name = ET.SubElement(people,'name')
name.text = 'Lucy'
age = ET.SubElement(people,'age')
age = '18'
gender = ET.SubElement(people,'gender')
gender.text = 'female'
et = ET.ElementTree(root)
et.write('xmltest.xml',encoding='utf8',xml_declaration=True)
ET.dump(root)