Python模块_XML模块

XMl是早期大家都在使用的标签语言,所以一直延用至今

<?xml version="1.0" encoding="utf-8" ?>
<data>
    <country name="China">
        <gdp>666</gdp>
        <peolpe>123456789</peolpe>
        <neighbor name="Japan" direcion = "E"/>
    </country>
    <country name="Korea">
        <gdp>666</gdp>
        <peolpe>234234</peolpe>
        <neighbor name="China" direcion = "N"/>
    </country>
    <country name="ChaoXian">
        <gdp>666</gdp>
        <peolpe>112233</peolpe>
        <neighbor name="Korea" direcion = "W"/>
    </country>
</data>

 

 

读取XML....查!

import xml.etree.ElementTree as ET
tree_data = ET.parse("xml_lesson")
root  = tree_data.getroot()
print("'xml_lesson'的根标签是:<",root.tag,">")

#遍历xml文档
for child in root:
    print("根标签下的 子标签是:<",child.tag,">\n",
          "子 标签的属性是:<",child.attrib,">") #tag标签名称,attrib标签属性(字典形式)
    for gra_chile in child:
        print("子标签下的 孙标签是:<",gra_chile.tag,">\n","孙 标签的属性是:<",
              gra_chile.attrib,">","子标签的内容是:",gra_chile.text) #text是标签里的文档内容
print("-"*50)
#只遍历country节点
for node in root.iter("country"):
    print(node.tag,"country的属性是:",node.attrib)
print("-" * 50)
#只遍历people节点
for node in root.iter("peolpe"):
    print(node.tag,"people节点的内容是:",node.text)

 

改!

#改people的text内容!
for node1 in root.iter('people'):
    new_people = int(node1.text) + 666
    print(new_people)
    node1.text = str(new_people)
    node1.set("updated","yes")

tree_data.write("new_xml.xml",encoding="utf-8")

 

删!

#删!
for country in root.findall("country"):
    gdp = int(country.find("gdp").text)
    if gdp > 66:
        root.remove(country)
        
tree_data.write("remove_xml.xml")

 

增!

#增!创建xml
namelist_xml = ET.Element("namelist")
name = ET.SubElement(namelist_xml,"name",attrib={"enrolled":"yes","update":"no"})
name.text = "James"
age = ET.SubElement(namelist_xml,"age",attrib={"checked":"no"})
age.text = "18"
sex = ET.SubElement(namelist_xml,"sex")
sex.text = "man"

et = ET.ElementTree(namelist_xml) #生成 文档对象 
et.write("add_xml.xml",encoding="utf-8",xml_declaration=True) #把对象写入硬盘

 

posted on 2019-07-10 16:12  詹生  阅读(143)  评论(0编辑  收藏  举报

导航