1. 程式人生 > >xml模塊 增刪改查

xml模塊 增刪改查

try 生成 模塊 code out move span none ati

import xml.etree.ElementTree as ET

tree = ET.parse("xml test") #open
root = tree.getroot() #f.seek(0)
#print(dir(root))
print(root)
#
# #遍歷xml文檔
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("xml test")
root = tree.getroot() #f.seek(0)


# #修改
# for node in root.iter(‘year‘):
#     new_year = int(node.text) + 1
#     node.text = str(new_year)
#     node.set("attr_test","yes")



#刪除node
for country in
root.findall(country): rank = int(country.find(rank).text) if rank > 50: root.remove(country) tree.write(output.xml)

# _*_coding:utf-8_*_
# created by Alex Li on 10/17/17

import xml.etree.ElementTree as ET


root = ET.Element("namelist") #root

name = ET.SubElement(root,"name
",attrib={"enrolled":"yes"}) age = ET.SubElement(name,"age",attrib={"checked":"no"}) sex = ET.SubElement(name,"sex") n = ET.SubElement(name,"name") n.text = "Alex Li" sex.text = male name2 = ET.SubElement(root,"name",attrib={"enrolled":"no"}) age = ET.SubElement(name2,"age") age.text = 19 et = ET.ElementTree(root ) #生成文檔對象 et.write("build_out.xml", encoding="utf-8",xml_declaration=True)

xml模塊 增刪改查