一、xml介绍

xml是实现不同语言或者程序直接进行数据交换的协议,跟json差不多,单json使用起来更简单。不过现在还有很多传统公司的接口主要是xml

xml跟html都是标签语言

我们主要学习的是ElementTree。是Python的xml处理模块,他提供了一个轻量级的对象模型,在使用ElementTree模块时,需要import xml.etree.ElementTre

ElementTree相当于整个xml的节点数,而Element表示节点树中的一个单独节点

我们看下面的xml文本,标签分为两种。

1、自闭和标签<rank updated="yes">2</rank>

2、非自闭和标签<neighbor direction="E" name="Austria" />

xml文件

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

二、xml.etree.ElementTree模块的具体使用

1、打印跟标签的名字

import xml.etree.ElementTree as ET #导入模块,名字太长了,把这个模块名重命名为ET
tree = ET.parse("xml_lesson.xml")#parse解析,用ET模块下的parse这个方法把xml文件解析开,解析开拿到一个tree,tree就是一个对象
root = tree.getroot()#这个对象可以调用方法,getroot就是根的意思
print(root.tag)#root这个对象有一个属性tag,tag的值就是根标签的名字 结果:
data

什么是标签,什么是属性,举个例子

<country name="Liechtenstein">

conuntry是标签

name="Liechtenstein" 是这个标签的属性

<neighbor direction="W" name="Costa Rica" />

neighbor是标签

direction="W" name="Costa Rica"  这2个都是标签的属性

2、用for循环查看root下面试什么东西

for n in root:
print(n) 结果:
<Element 'country' at 0x0000000000E339F8> <Element 'country' at 0x0000000000E38408> <Element 'country' at 0x0000000000E38598>

这三个地址指的就是面向对象,打印下这三个标签的名字,用tag这个属性就可以了

for n in root:
print(n.tag) 结果:
country country country

在打印下country下面的标签

for n in root:
for i in n:
print(i.tag) 结果:
rank year gdppc neighbor neighbor rank year gdppc neighbor rank year gdppc neighbor neighbor

3、打印标签属性attrib

打印country的属性

for n in root:
print(n.attrib) 结果:
{'name': 'Liechtenstein'} {'name': 'Singapore'} {'name': 'Panama'}

在打印country里面的对象的属性

for n in root:
for i in n:
print(i.attrib) 结果:
{'updated': 'yes'} {'updated': 'yes'} {} {'name': 'Austria', 'direction': 'E'} {'name': 'Switzerland', 'direction': 'W'} {'updated': 'yes'} {'updated': 'yes'} {} {'name': 'Malaysia', 'direction': 'N'} {'updated': 'yes'} {'updated': 'yes'} {} {'name': 'Costa Rica', 'direction': 'W'} {'name': 'Colombia', 'direction': 'E'}

4、text标签实际包裹的内容

for n in root:
for i in n:
print(i.text) 结果:
data
2
2010
141100
None
None
5
2013
59900
None
69
2013
13600
None
None

5、iter

for n in root.iter("year"):
print(n.tag,n.text) 结果:
data
year 2010
year 2013
year 2013

6、对xml文件数据进行修改操作

import xml.etree.ElementTree as ET #导入模块,名字太长了,把这个模块名重命名为ET

tree = ET.parse("xml_lesson.xml")#parse解析,用ET模块下的parse这个方法把xml文件解析开,
#解析开拿到一个tree,tree就是一个对象
root = tree.getroot()#这个对象可以调用方法,getroot就是根的意思
# print(root.tag)#root这个对象有一个属性tag,tag的值就是根标签的名字 for n in root.iter("year"):
new_year=int(n.text)+1
n.text=str(new_year)#修改year标签的text属性
n.set("updated1","yes")#给year这个标签增加一个属性
tree.write("xml_lesson.xml")#直接把修改的写入到文件中

7、对xml文件进行删除操作,比如删除排名大于50的国家,需要取到每个conutry中的rank的text

import xml.etree.ElementTree as ET #导入模块,名字太长了,把这个模块名重命名为ET

tree = ET.parse("xml_lesson.xml")#parse解析,用ET模块下的parse这个方法把xml文件解析开,
#解析开拿到一个tree,tree就是一个对象
root = tree.getroot()#这个对象可以调用方法,getroot就是根的意思
# print(root.tag)#root这个对象有一个属性tag,tag的值就是根标签的名字 for n in root.findall("country"):#找到所有的country
rank=int(n.find("rank").text)#找到所有的rank的text值
if rank > 50:#判断值大于50的
root.remove(n)#就删除country这个标签
tree.write("xml_lesson.xml")#写入文件

删除之后,文件里面只有2个country了

<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year updated="yes" updated1="yes">2012</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year updated="yes" updated1="yes">2015</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
</data>

8、如何通过模块创建xml文件呢

import xml.etree.ElementTree as ET #导入模块,名字太长了,把这个模块名重命名为ET
new_xml=ET.Element("namelist")#创建了一个根节点
#相当于创建了<namelist></namelist>
name=ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
#创建一个子标签name,然后增加一个属性
age=ET.SubElement(name,"age",attrib={"checked":"no"})
sex=ET.SubElement(name,"sex")
sex.text="28" et=ET.ElementTree(new_xml)#生成文档对象
et.write("test.xml",encoding="utf8",xml_declaration=True)

查看下生成的text.xml这个文件内容

<namelist>

<name enrolled="yes">

<age checked="no"/>

<sex>28</sex>

</name>

</namelist>

day22 Pythonpython 本文xml模块的更多相关文章

  1. day22 Pythonpython 本文json模块

    json模块 •应用场景: json模块主要用于处理json格式的数据,可以将json格式的数据转化为python的字典,便于python处理,同时也可以将python的字典或列表等对象转化为json ...

  2. day22 Pythonpython 本文sys模块

    一.sys模块 用来提供对Python解释器相关的操作 sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit(0) sys.versio ...

  3. day22 Pythonpython random随机模块:略!!!本文os模块

    OS模块 用于提供系统级别的操作: os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录:相 ...

  4. day23 Pythonpython 本文re模块

    re模块用于对python的正则表达式的操作. 字符: . 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字 \s 匹配任意的空白符 \d 匹配数字 \b 匹配单词的开始或结束 ^ 匹配 ...

  5. Python常用内置模块之xml模块

    xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言.从结构上,很像HTML超文本标记语言.但他们被设计的目的是不同的,超文本标记语言被设计用来显示 ...

  6. oop、configparser、xml模块

    本节大纲:一:在python中,有两种编程思想.1:函数式编程.2:oop.无论是函数式编程还是oop都是相辅相成.并不是说oop比函数式编程就好.各有各的优缺点.在其他语言中java等只能以面向对象 ...

  7. python解析xml模块封装代码

    在python中解析xml文件的模块用法,以及对模块封装的方法.原文转自:http://www.jbxue.com/article/16586.html 有如下的xml文件:<?xml vers ...

  8. s14 第5天 时间模块 随机模块 String模块 shutil模块(文件操作) 文件压缩(zipfile和tarfile)shelve模块 XML模块 ConfigParser配置文件操作模块 hashlib散列模块 Subprocess模块(调用shell) logging模块 正则表达式模块 r字符串和转译

    时间模块 time datatime time.clock(2.7) time.process_time(3.3) 测量处理器运算时间,不包括sleep时间 time.altzone 返回与UTC时间 ...

  9. python全栈开发-hashlib模块(数据加密)、suprocess模块、xml模块

    一.hashlib模块 1.什么叫hash:hash是一种算法(3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法 ...

随机推荐

  1. Hibernate(链接数据库方便得多)!

    首先让我们看一下配置文件,我这里先是用struts搞得controller,不明白struts的可以去百度一下这里就不讲解了: 之后我们需要做一个hibernate的配置文件内容如下(这里链接的是my ...

  2. 04-HTML-图片标签

    <html> <head>  <title>图片标签学习</title>  <meta charset="utf-8"/> ...

  3. MMU学习总结

    待完善 一.MMU主要完成哪些事务? 二.PowerPC上的BAT.LAW是做什么用的? 三.

  4. 浅谈SnackBar(Toast大兄弟)

    SnackBar是 Android Support Library 22.2.1 里面新增提供的一个控件,我们可以简单的把它理解成一个加强版的Toast,或者是一个轻量级的Dialog. 特点: .S ...

  5. MySQL 安装及卸载详细教程

    本文采用最新版MySQL8版本作为安装教程演示,本人亲试过程,准确无误.可供读者参考. 下载 官网下载 --> 社区免费服务版下载. 下载Windows安装程序MySQL Installer M ...

  6. HDU 1086

    You can Solve a Geometry Problem too Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/3 ...

  7. spring MVC,controller中获得resuqest和response的方式

    package com.devjav.spring; import java.util.List; import java.util.Locale; import javax.servlet.http ...

  8. c/c++ 标准库 map multimap元素访问

    标准库 map multimap元素访问 一,map,unordered_map下标操作 下标操作种类 功能描述 c[k] 返回关键字为k的元素:如果k不在c中,添加一个关键字为k的元素,并对其初始化 ...

  9. strlen strcat strcpy strcmp 自己实现

    strlen strcat strcpy strcmp 自己实现 strlen include <stdio.h> #include <string.h> #include & ...

  10. 【PAT】 B1006 换个格式输出整数

    超简单题 //直接将各位分开,分别用for循环输出 #include<stdio.h> int main(){ int num; scanf("%d",&num ...