XML模块

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

# import xml.etree.ElementTree as ET
#
# tree = ET.parse('xml_lesson') # parse('文件名')方法,对xml文件进行解析
# root = tree.getroot() # getroot()方法,获取数据的根目录信息
# print(root.tag) # tag表示标签,根节点标签为data,三个子节点标签为country

# 遍历xml文档
# for i in root:
#  for j in i:
#     # print(j.tag) # 这里打印的是三个子节点下面信息的标签--->第一个子节点下面信息的标签rank,year,gdppc,neighbor,neighbor
#     # print(j.attrib) # 这里打印的是三个子节点下面信息的属性--->第一个子节点下面信息的属性{'updated': 'yes'},{},{},{'name': 'Austria', 'direction': 'E'}, {'name': 'Switzerland', 'direction': 'W'}
#     print(j.text) # 这里打印的是三个子节点下面信息的数据--->第一个子节点下面信息的数据2,2008,141100,None,None


# 遍历year节点
# for x in root.iter('year'): # iter('标签')从外往里找相对应的标签
#  print(x.tag, x.text) # 此条数据没有属性


# 修改
# for i in root.iter('year'):
#  # new_year = int(i.text) + 1
#  # i.text = str(new_year)
#  i.text = str(int(i.text) + 1) # 对标签数据进行修改,读取出来是字符串,修改也应是字符串
#  i.set('updated', 'yes') # 对标签数据加入属性,相当于updated="yes"
# tree.write('xml_lesson') # 最后写入文件,文件名如果不和之前的一样,那么会生成一个新文件,内容是修改过后的;


# 删除
# for a in root.findall('country'): # findall('标签')寻找多个
#  b = int(a.find('rank').text) # find('标签')寻找一个
#  if b > 50:
#     root.remove(a)
# tree.write('xml_lesson')



'''自己创建xml文档'''
# import xml.etree.ElementTree as ET
#
# new_xml = ET.Element("namelist")
# name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
# 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)  # 打印生成的格式
# xml文档里的数据
<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>
while True: print('studying...')
原文地址:https://www.cnblogs.com/xuewei95/p/14539084.html