xml模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,
不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
xml的格式如下,就是通过<>节点来区别数据结构的:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml
遍历
import xml.etree.ElementTree as ET tree = ET.parse("xml test") # 打开xml文件
root = tree.getroot() # 得到根节点
# print(dir(root))
print(root.tag)
# 遍历xml文档
for child in root:
print('----------',child.tag, child.attrib) # 打印country节点
for i in child:
print(i.tag,i.text)
修改和删除xml文档内容
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) + 5
node.text = str(new_year) # 修改内容
node.set("attr_test","false")
tree.write('output.xml') # 写入文件 # #删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country) tree.write('output.xml')
新建xml
import xml.etree.ElementTree as ET root = ET.Element("namelist") # 创建root name = ET.SubElement(root,"name",attrib={"enrolled":"yes"}) # 创建child--name
age = ET.SubElement(name,"age",attrib={"checked":"no"}) # 创建name child--age,sex,name
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 = '' et = ET.ElementTree(root) # 生成文档对象
et.write("build_out.xml", encoding="utf-8",xml_declaration=True)
由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式
import xml.etree.ElementTree as ET
from xml.dom import minidom def subElement(root, tag, text):
ele = ET.SubElement(root, tag)
ele.text = text def saveXML(root, filename, indent="\t", newl="\n", encoding="utf-8"):
rawText = ET.tostring(root)
dom = minidom.parseString(rawText)
with open(filename, 'w') as f:
dom.writexml(f, "", indent, newl, encoding) root = ET.Element("namelist") to = root.makeelement("to", {})
to.text = "peter"
root.append(to) name = ET.SubElement(root,"name",attrib={"enrolled":"yes"}) # 创建child--name
age = ET.SubElement(name,"age",attrib={"checked":"no"}) # 创建name child--age,sex,name
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 = '' # et = ET.ElementTree(root) # 生成文档对象 # 保存xml文件
saveXML(root, "note.xml")