一、概念
xmL是实现不同语言或程序之间进行数据交换的协议,跟json差不多
但json更简单,不过xml出现太早,很多地方已广泛使用
tag: 标签 attrib:属性 text:内容
二、获取标签
import xml.etree.ElementTree as xm
tree = xm.parse("xml_lesson")
root = tree.getroot()
print(root.tag) #得到跟标签,data
for i in root:
print(i.tag) #遍历data 得到子标签 country
for j in i:
print(j.tag) #遍历country,得到country的子标签
三、获取属性
import xml.etree.ElementTree as xm
tree = xm.parse("xml_lesson")
root = tree.getroot()
print(root.tag) #得到跟标签,data
for i in root: #遍历data 得到country
print(i.attrib) #获得country 的属性
for j in i: #遍历country得到下面子标签
print(j.attrib) #获得下面子标签的属性
四、获取内容
import xml.etree.ElementTree as xm
tree = xm.parse("xml_lesson")
root = tree.getroot()
print(root.tag) #得到跟标签,data
for i in root: #遍历data 得到country
for j in i: #遍历country得到下面子标签
print(j.text) #获得下面子标签的内容
五、只遍历year标签
import xml.etree.ElementTree as xm
tree = xm.parse("xml_lesson")
root = tree.getroot()
for node in root.iter('year'):
print(node.tag, node.text) #获取year的标签和属性
六、修改
import xml.etree.ElementTree as xm
tree = xm.parse("xml_lesson")
root = tree.getroot()
for node in root.iter('year'):
new_year = int(node.text) + 1 #把year内容加1
node.text = str(new_year)
node.set("updata", "year")
tree.write("xml_lesson") #覆盖掉原来的文件
七、删除
import xml.etree.ElementTree as xm
tree = xm.parse("xml_lesson")
root = tree.getroot()
for country in root.findall('Country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country) #把rank大于50的country删掉
tree.write("xml_lesson")
八、创建xml文件
import xml.etree.ElementTree as xm
new_xml = xm.Element("namelist") #生成根
name = xm.SubElement(new_xml, "name", attrib = {"enrolled": "yes"})
age = xm.SubElement(name, "age", attrib = {"checked":"no"})
sex = xm.SubElement(name, "sex")
sex.text = "22"
name2 = xm.SubElement(new_xml, "name", attrib = {"enrolled": "no"})
age = xm.SubElement(name2, "age")
age.text = "19"
et = xm.ElementTree(new_xml) #生成文档对象
et.write("text.xml", encoding = "utf -8", xml_declaration = True)
xm.dump(new_xml) #打印生成的格式