深入了解python之XML操作


本文摘自php中文网,作者零到壹度,侵删。

这篇文章主要介绍了深入了解python之Xml操作,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

读取xml内容:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

-*- coding:utf-8 -*-

# Author: Evan Mi

import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')

root = tree.getroot()

print(root.tag)

# 一个节点有tag、attrib、text三个值

# tag是标签的名字

# text是标签的内容

# attrib是标签属性的字典,通过字典的get('key')来获取对应的属性的值

 

# 直接for chile in parent 来遍历节点下的子节点

for child in root:

    print(child.tag, child.attrib)

    for elem in child:

        print(elem.tag, elem.text, elem.attrib)

 

# 只遍历year节点

for node in root.iter('year'):

    print(node.tag, node.text)

生成xml内容:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

# -*- coding:utf-8 -*-

# Author: Evan Mi

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('te.xml', encoding='utf-8', xml_declaration=True)

 

ET.dump(new_xml)  # 打印生成的格式

修改、删除xml内容:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

# -*- coding:utf-8 -*-

# Author: Evan Mi

import xml.etree.ElementTree as ET

 

tree = ET.parse('test.xml')

root = tree.getroot()

 

# 修改

for node in root.iter('year'):

    new_year = int(node.text) + 1

    node.text = str(new_year)   # 修改内容

    node.set("updated", "yes")  # 修改属性

 

tree.write('tt.xml')

 

 

# 删除

for country in root.findall('country'):

    rank = int(country.find('rank').text)

    if rank > 50:

        root.remove(country)

tree.write('tt1.xml')

相关推荐:

Python & XML

python读写xml文件

Python之XML文件操作

以上就是深入了解python之XML操作的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

如何使用 pylint 来规范 Python 代码风格(来自ibm)_Python

不可错过的十本Python好书

Python源程序执行的方式有什么

Python安装路径怎么找

解析Python代码注释规范代码

Python通过什么来判断操作是否在分支结构中

成为Python大牛必不可少的几款编辑器

Python数据结构与算法之常见的分配排序法示例【桶排序与基数排序】_Python

Python中的排序操作和heapq模块的介绍(代码示例)

ansible作为Python模块库使用的方法

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...