xml模块

 

import xml.etree.ElementTree as ET

'查数据'
# tree = ET.parse("xmltest.xml")
# root = tree.getroot()   #getroot()  获取根节点
# print(root.tag)         #tag 获取标签
#
# for i in root:
#     for j in i:
# #        print(j.attrib)     #attrib 获取属性
#         print(j.text)        #text 获取内容  两个标签中间的文本

# for node in root.iter('year'):      #iter获取指定标签的节点
 #     print(node.tag,node.text)

'改数据'
# for node in root.iter('year'):
#     new_year = int(node.text) + 1
#     node.text = str(new_year)
#     node.set("updated", "yes")      #设置属性 健-值
#
# tree.write("xmltest.xml")


'删数据'
# for country in root.findall('country'):       #findall不能越级找标签 iter遍历所有标签
#     rank = int(country.find('rank').text)
#     if rank > 50:
#         root.remove(country)
#
# tree.write('output.xml')


'创建xml文件'
import xml.etree.ElementTree as ET

new_xml = ET.Element("namelist")      #创建一个标签名为namelist的节点 ,节点名为new_xml
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})         #在new_xml的节点下创建子节点 标签名为name 添加属性 enrolled="yes"
                                                                            #其中new_xml为要处理的对象,"name"为标签名,attrib为添加属性
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'

et = ET.ElementTree(new_xml)  # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)

ET.dump(new_xml)  # 打印生成的格式

 

posted @ 2022-03-18 19:28  呱呱、、  阅读(24)  评论(0编辑  收藏  举报