python内置模块之XML模块

#xml和json 一样都是可以跨平台的,只是xml相比较,老一点
import xml.etree.ElementTree as ET
a=ET.parse("first_xml.xml")#加载一个文件
root=a.getroot()
print(root)#一个xml文件
print(root.tag)#xml头文件名
for i in root:#进入xml文件中
    print(i.attrib)#打印属性
    for j in i:#进入下一层标签中
        print(j.tag,j.text,j.attrib)#j.tag标签名,j.text值,j,attrib 属性


# 如果只想调用标签属性
for x in root.iter('people'):#是把下一层变成字典形式,然后返回
    print(x)
    print(x.text,x.tag)



#xml文件的修改
for y in root.iter("people"):
    y.set("author","gw")#添加属性
    y1=int(y.text)+1#取值,因为y.text是str模型,所以要转成int型
    y.text=str(y1)#写入
a.write("first_xml")#写入一个文件,w方式,会覆盖文件中的内容,相当于把修改后的文件取一个别名


#xml文件删除
for c in root.findall("country"):#查找所有有country的标签
    r=int(c.find("people").text)#取值
    print(r)
    if r >7:
        root.remove(c)
a.write("second_xml")#

下面是从python中生成xml


import xml.etree.ElementTree as ET
main_xml=ET.Element("earth")#建立第一个标签
one_xml=ET.SubElement(main_xml,"one_xml",attrib={"country":"A"})#建立第二个标签,其中attrib代表的是属性,添加一个字典的形式进去
people1=ET.SubElement(one_xml,"people")#建立第三个标签
people1.text="50"#记住赋值是字符串
et=ET.ElementTree(main_xml)#生成一个标签,只需要写第一个标签就行了,因为类似于递归,会不断调用下一层
et.write("test.xml",encoding="utf-8",xml_declaration=True)#写入,其中xml_delaration代表的是最开始的注释

文件的方法

猜你喜欢

转载自blog.csdn.net/qq_37181884/article/details/81671053