xml 模块 - 图1


一、xml简介

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
xml的格式如下,就是通过<>节点来区别数据结构的:

  1. <?xml version="1.0"?>
  2. <data>
  3. <country name="Liechtenstein">
  4. <rank updated="yes">2</rank>
  5. <year>2008</year>
  6. <gdppc>141100</gdppc>
  7. <neighbor name="Austria" direction="E"/>
  8. <neighbor name="Switzerland" direction="W"/>
  9. </country>
  10. <country name="Singapore">
  11. <rank updated="yes">5</rank>
  12. <year>2011</year>
  13. <gdppc>59900</gdppc>
  14. <neighbor name="Malaysia" direction="N"/>
  15. </country>
  16. <country name="Panama">
  17. <rank updated="yes">69</rank>
  18. <year>2011</year>
  19. <gdppc>13600</gdppc>
  20. <neighbor name="Costa Rica" direction="W"/>
  21. <neighbor name="Colombia" direction="E"/>
  22. </country>
  23. </data>

二、Python使用xml

xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:

  1. # print(root.iter('year')) #全文搜索
  2. # print(root.find('country')) #在root的子节点找,只找一个
  3. # print(root.findall('country')) #在root的子节点找,找所有
  4. import xml.etree.ElementTree as ET
  5. tree = ET.parse("xmltest.xml")
  6. root = tree.getroot()
  7. print(root.tag)
  8. #遍历xml文档
  9. for child in root:
  10. print('========>', child.tag, child.attrib, child.attrib['name'])
  11. for i in child:
  12. print(i.tag, i.attrib, i.text)
  13. #只遍历year 节点
  14. for node in root.iter('year'):
  15. print(node.tag, node.text)
  16. #---------------------------------------
  17. import xml.etree.ElementTree as ET
  18. tree = ET.parse("xmltest.xml")
  19. root = tree.getroot()
  20. #修改
  21. for node in root.iter('year'):
  22. new_year = int(node.text) + 1
  23. node.text = str(new_year)
  24. node.set('updated', 'yes')
  25. node.set('version', '1.0')
  26. tree.write('test.xml')
  27. #删除node
  28. for country in root.findall('country'):
  29. rank = int(country.find('rank').text)
  30. if rank > 50:
  31. root.remove(country)
  32. tree.write('output.xml')
  33. #在country内添加(append)节点year2
  34. import xml.etree.ElementTree as ET
  35. tree = ET.parse("a.xml")
  36. root = tree.getroot()
  37. for country in root.findall('country'):
  38. for year in country.findall('year'):
  39. if int(year.text) > 2000:
  40. year2 = ET.Element('year2')
  41. year2.text = '新年'
  42. year2.attrib = {'update': 'yes'}
  43. country.append(year2) #往country节点下添加子节点
  44. tree.write('a.xml.swap')

三、自己创建xml文档

  1. import xml.etree.ElementTree as ET
  2. new_xml = ET.Element("namelist")
  3. name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
  4. age = ET.SubElement(name, "age", attrib={"checked": "no"})
  5. sex = ET.SubElement(name, "sex")
  6. sex.text = '33'
  7. name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
  8. age = ET.SubElement(name2, "age")
  9. age.text = '19'
  10. et = ET.ElementTree(new_xml) #生成文档对象
  11. et.write("test.xml", encoding="utf-8", xml_declaration=True)
  12. ET.dump(new_xml) #打印生成的格式