python学习,day5:内置模块(xml文件的创建和修改)
创建
# coding=utf-8 # Author: RyAn Bi import xml.etree.ElementTree as ET new_xml = ET.Element('namelist') #根节点 personinfo = ET.SubElement(new_xml , 'personinfo', attrib={"enrolled": "yes"}) #new_xml下的子节点,叫personinfo name = ET.SubElement(personinfo,'name') age = ET.SubElement(personinfo, 'age') #personinfo 下的子节点,叫age sex = ET.SubElement(personinfo, 'sex') #personinfo下的子节点,叫sex name.text = 'bijibin' age.text = '33' #给age赋值 personinfo2 = ET.SubElement(new_xml , 'personinfo', attrib={"enrolled": "yes"}) name = ET.SubElement(personinfo2,'name', attrib={"enrolled": "yes"}) #new_xml下的子节点,叫personinfo2 age = ET.SubElement(personinfo2,'age') #personinfo2 下的子节点,叫age sex = ET.SubElement(personinfo2,'sex') #personinfo2 下的子节点,叫sex name.text='ryan' age.text = '11' #给age赋值 et = ET.ElementTree(new_xml) #生成文档对象 et.write('test.xml', encoding='utf-8', xml_declaration = True) #声明格式和版本,写入test.xml ET.dump(new_xml) #打印生成格式
修改
import xml.etree.ElementTree as et tree = et.parse('xmltest.xml') root = tree.getroot() # for node in root.iter('year'): #修改year # new_year = int (node.text)+1 #每年都+1 # node.text = str(new_year) # 把新的值附上去 # node.set('updated','yes') #给year增加一个属性 # # tree.write('xmltest.xml') #写回原文件 for country in root.findall('country'): #查找当前element的孩子的属于某个tag的elemen rank = int(country.find('rank').text) #找到country中rank文档 if rank > 50: #找到>50的 root.remove(country) #删除这个country tree.write('output.xml') #输出到新的xml
处理
# coding=utf-8 # Author: RyAn Bi import xml.etree.ElementTree as ET #导入包 tree = ET.parse('xmltest.xml') #导入要处理的文件 root = tree.getroot() #定义根目录 print(root) print(root.tag) for child in root: print(child.tag,child.attrib) for i in child: print(i.tag,i.attrib,i.text) #打印标签,打印属性,打印文档 for j in i: print(j.tag,j.attrib,j.text) for node in root.iter('year'): print(node.tag,node.text)