huakai 2020-02-13
import xml.etree.ElementTree as ET
data=ET.parse(‘xml_lesson‘)
root=data.getroot()
for i in root:
for j in i:
print(j.tag)
for i in root:
print(i.attrib)
for i in root:
for j in i:
print(j.text)
for label in root.iter(‘year‘):
print(label.tag,label.text)
-------------------------------------------------
for label in root.iter(‘year‘):
year_text=int(label.text)+1
label.text=str(year_text)
label.set(‘updated‘,‘yes‘)
tree.write(‘xml_lesson‘) //修改
--------------------------------------------------
for country in root.findall(‘country‘):
data=int(country.find(‘rank‘).text)
if data>50:
root.remove(country)
tree.write(‘abc.xml‘) //删除
--------------------------------------------------
import xml.etree.ElementTree as ETdata=ET.Element(‘data‘)country=ET.SubElement(data,‘country‘,attrib={‘name‘:‘Singapore‘})rank=ET.SubElement(country,‘rank‘,attrib={‘updated‘:‘yes‘})year=ET.SubElement(country,‘year‘,attrib={‘updated‘:‘yes‘})year.text=‘2010‘et=ET.ElementTree(data)et.write(‘test1.xml‘,encoding=‘utf-8‘,xml_declaration=True) //新建一个xml文档‘‘‘
<?xml version=‘1.0‘ encoding=‘utf-8‘?><data> <country name="Singapore"> <rank updated="yes" /> <year updated="yes">2010</year> </country></data>‘‘‘