xml 创建 和 处理 及其修改

#创建xml

import xml.etree.ElementTree as ET

new_xml = ET.Element('namelist')

personinfo = ET.SubElement(new_xml, 'personinfo', attrib = {'enroll' :yes})

age = ET.SubElement(personinfo,'name', attrib = {'check':'no'})

name =  ET.SubElement(personinfo,'age', attrib = {'check':'no'})

name.text = 'Alex li'

age.text = '23'

prosoninfo2 =  ET.SubElement(new_xml, 'personinfo', attrib = {'enroll' :yes})

age = ET.SubElement(personinfo2,'name', attrib = {'check':'no'})

name =  ET.SubElement(personinfo2,'age', attrib = {'check':'no'})

name.text = 'Alex li'

age.text = '23'

et = ET.ElementTree(new_xml)

et.write('test.xml', encoding = 'utf-8), xml_declaration = True

ET.dump(new_xml)

#xml 打开和遍历

Import xml.etree.ElementTree as ET

tree = ET.parse('xmltest.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, i.attrib)

for node in root.iter('year'):  #只遍历year节点

print(node.tag, node.text)

# xml修改

import xml.etree.ElementTree as ET

tree = ET.parse('xmltest.xml')
root = tree.getroot()

for node  in root.iter('year'):
     new_year = int(node.text) + 1

node.text = str(new_year)

node.set = ('update', 'yes')

for country in root.findall('country')

rank = int(country.find('rank').text)

if rank > 50

root.remove(country)

tree.wirte('output.xml')

上一篇:LINUX查看服务器硬件配置(转)


下一篇:Hadoop Single Node Setup(hadoop本地模式和伪分布式模式安装-官方文档翻译 2.7.3)