导入模块:
import xml.etree.ElementTree as ET
创建xml文件:
new_xml = ET.Element("namelist") # 创建根节点 userinfo = ET.SubElement(new_xml, "userinfo", attrib={"enrolled": "yes"}) # 给new_xml创建子节点,userinfo:节点名,attrib:属性及值 name = ET.SubElement(userinfo, "name") # 给userinfo创建子节点,name:节点名 name.text = 'name1' age = ET.SubElement(userinfo, "age", attrib={"checked": "no"}) # 给userinfo创建子节点,age:节点名,attrib:属性及值 age.text = '23' # 给age节点添加节点内容 sex = ET.SubElement(userinfo, "sex") # 给userinfo创建子节点,sex:节点名 sex.text = '男' userinfo2 = ET.SubElement(new_xml, "userinfo", attrib={"enrolled": "no"}) # 给new_xml创建子节点,userinfo:节点名,attrib:属性及值 name = ET.SubElement(userinfo2, "name") # 给userinfo2创建子节点,name:节点名 name.text = 'name2' age = ET.SubElement(userinfo2, "age") # 给userinfo2创建子节点,age:节点名 age.text = '24' # 给age节点添加节点内容 sex = ET.SubElement(userinfo2, "sex") # 给userinfo创建子节点,sex:节点名 sex.text = '女' userinfo3 = ET.SubElement(new_xml, "userinfo", attrib={"enrolled": "yes"}) # 给new_xml创建子节点,userinfo:节点名,attrib:属性及值 name = ET.SubElement(userinfo3, "name") # 给userinfo3创建子节点,name:节点名 name.text = 'name3' age = ET.SubElement(userinfo3, "age") # 给userinfo3创建子节点,age:节点名 age.text = '26' # 给age节点添加节点内容 et = ET.ElementTree(new_xml) # 生成文档对象 et.write("xmltest.xml", encoding="utf-8", xml_declaration=True) # 写入xmltest.xml文件,xml_declaration指定为xml格式,文件头:<?xml version='1.0' encoding='utf-8'?> ET.dump(new_xml) # 打印生成的格式
执行结果:
读取xml文件:
tree = ET.parse('xmltest.xml') # 打开xml文件 root = tree.getroot() # 获取根节点 # root.tag 获取根节点标签 print(root.tag) # 获取根节点标签 # namelist # 遍历xml文档 # text 获取标签内容 # attrib 获取标签属性值 for child in root: print(child.tag, child.attrib) # 获取标签名及属性值 for i in child: print(i.tag, i.text) # 获取标签名及标签内容 # 遍历指定节点(name) for node in root.iter('name'): print(node.tag, node.text)
执行结果:
修改xml内容:
tree = ET.parse("xmltest.xml") # 打开xml文件 root = tree.getroot() # 获取根节点 # 修改,所有age值加1 for node in root.iter('age'): new_rank = int(node.text) + 1 node.text = str(new_rank) # 修改age节点的内容 node.set("sexvalue", "M/W") # 给sex节点添加属性 tree.write("xmltest.xml")
执行结果:
删除xml节点:
tree = ET.parse('xmltest.xml') # 打开xml文件 root = tree.getroot() # 获取根节点 # root.tag 获取根节点标签 for userinfo in root.findall('userinfo'): # root.findall 找到所有的 userinfo 节点 rank = int(userinfo.find('age').text) # 获取age的值 if rank > 25: root.remove(userinfo) # 删除age>25的userinfo节点 tree.write('output.xml') # 删除之后的内容写入output.xml中,也可写入源文件 tree.write('xmltest.xml')
执行结果: