标签:led convert 功能 move root max 获取 添加 打印
这里主要讲解xml模块下的etree.ElementTree类。
具体代码如下
import xml.etree.ElementTree as XM
namelist1 = XM.Element("namelist1")#创建标签
name1 = XM.SubElement(namelist1,"name",attrib={"enrolled":"yes"})#创建子标签
age1 = XM.SubElement(name1,"age",attrib={"checked":"33"})#创建下一级子标签
sex1 = XM.SubElement(name1,"sex",)#创建最后一级子标签
sex1.text = ‘man‘#对最后一级子标签添加text属性
name2 = XM.SubElement(namelist1,"name",attrib={"enrolled":"no"})
age2 = XM.SubElement(name2,"age",attrib={‘actual‘:‘19‘})
sex2 = XM.SubElement(name2,‘sex‘)
sex2.text = ‘gril‘
et = XM.ElementTree(namelist1) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
XM.dump(namelist1) #打印生成的格式
具体代码如下
xm_data = XM.parse(‘test.xml‘)
data_root = xm_data.getroot()#获取第一级标签
for i in data_root.iter(‘sex‘):
i.text = ‘Super‘ + i.text
# for j in data_root.iter(‘age‘):#遍历出的属性为字典类型,可参考字典修改方法进行修改。
# print(j.attrib)
xm_data.write(‘test.xml‘)
具体代码如下
xm_data = XM.parse(‘test.xml‘)
data_root = xm_data.getroot()#获取第一级标签
print(data_root)
for name in data_root:#遍历第一级标签
print(name.tag,name.attrib)
for age in name:#遍历第二级标签
print(age.tag,age.text)
for names in data_root.iter(‘name‘):#过滤性变遍历
print(names.tag,names.text)
具体代码如下 xmdata = XM.parse(‘test.xml‘) dataroot = xmdata.getroot()#获取第一级标签 for name in dataroot: for age in name.findall(‘age‘): if age.attrib.get(‘actual‘): name.remove(age) xm_data.write(‘test.xml‘)
标签:led convert 功能 move root max 获取 添加 打印
原文地址:http://www.cnblogs.com/single-boy/p/7616897.html