码迷,mamicode.com
首页 > 其他好文 > 详细

xml模块

时间:2018-08-07 20:40:13      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:gap   ted   处理   art   utf-8   tree   click   2.x   技术   

 

xml模块是一种文件数据处理格式的方法,常用与生成、解析或修改.xml配置文件

  1.常见的.xml配置文件格式如下

<admin>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</admin>

 

  2.xml模块的简单使用

# -*- coding:utf-8 -*-
# Author:Wong Du


import xml.etree.ElementTree as xet

tree = xet.parse(test.xml)        # 解析xml对象
root = tree.getroot()           # 读取xml文件内容
# print(root.tag)        #只显示第一层tag

for i in root:
    print(i.tag, i.attrib)
    for i1 in i:
        print(i1.tag,i1.attrib,i1.text)

for i in root.iter():       #获取所有层的tag
    print(i.tag)


# 修改
root.tag = admin
tree.write(test.xml)

# 删除
for i in root.iter():
    if direction in i.attrib:
        i.attrib.pop(direction)
tree.write(test1.xml)

 

  3. 用Python创建.xml文件小实例

# -*- coding:utf-8 -*-
# Author:Wong Du

import xml.etree.ElementTree as xet

new_xml = xet.Element(Earth)

Country = xet.SubElement(new_xml,Country,attrib={Cname:China})
Province = xet.SubElement(Country,Province,attrib={Pname:Guangdong})
Province2 = xet.SubElement(Country,Province,attrib={Pname:Shanghai})
Province3 = xet.SubElement(Country,Province,attrib={Pname:Beijing})
Province4 = xet.SubElement(Country,Province,attrib={Pname:Guangxi})
City = xet.SubElement(Province4,City,attrib={特色:旅游})
City.text = 桂林



xet_tree = xet.ElementTree(new_xml)
xet_tree.write(create.xml,encoding=utf-8,xml_declaration=True)

xet.dump(new_xml)
技术分享图片
<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<Earth>
    <Country Cname="China">
        <Province Pname="Guangdong" />
        <Province Pname="Shanghai" />
        <Province Pname="Beijing" />
        <Province Pname="Guangxi">
            <City 特色="旅游">桂林</City>
        </Province>
    </Country>
</Earth>
创建成功的.xml文件

 

xml模块

标签:gap   ted   处理   art   utf-8   tree   click   2.x   技术   

原文地址:https://www.cnblogs.com/Caiyundo/p/9438635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!