详解 Python 读写XML文件的实例
作者:Godliness丶 时间:2022-05-03 23:36:15
详解 Python 读写XML文件的实例
Python 生成XML文件
from xml.dom import minidom
# 生成XML文件方式
def generateXml():
impl = minidom.getDOMImplementation()
# 创建一个xml dom
# 三个参数分别对应为 :namespaceURI, qualifiedName, doctype
doc = impl.createDocument(None, None, None)
# 创建根元素
rootElement = doc.createElement('Pythons')
# 为根元素添加10个子元素
for pythonId in range(10):
# 创建子元素
childElement = doc.createElement('python')
# 为子元素添加id属性
childElement.setAttribute('id', str(pythonId))
# 将子元素追加到根元素中
rootElement.appendChild(childElement)
print(childElement.firstChild.data)
# 将拼接好的根元素追加到dom对象
doc.appendChild(rootElement)
# 打开test.xml文件 准备写入
f = open('test.xml', 'a')
# 写入文件
doc.writexml(f, addindent=' ', newl='\n')
# 关闭
f.close()
# 执行生成xml方法
generateXml()
python 读取XML文件
from xml.dom.minidom import parse
# 获取 python节点下得所有id属性
def getTagId():
# 获取test.xml文档对象
doc = parse("test.xml")
for node in doc.getElementsByTagName("python"):
# 获取标签ID属性
value_str = node.getAttribute("id")
# 打印输出
print(value_str)
# 获取属性ID
getTagId()
运行结果 – 生成xml文件如下
运行结果 – 读取xml文件如下
来源:http://blog.csdn.net/qq_878799579/article/details/74294503
标签:Python,XML
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP比你想象的好得多
2023-11-20 09:33:30
python将txt等文件中的数据读为numpy数组的方法
2022-04-20 14:08:10
Python字符串的全排列算法实例详解
2023-04-30 17:01:05
PyQt中使用QProcess运行一个进程的示例代码
2021-10-16 15:57:39
![](https://img.aspxhome.com/file/2023/9/101119_0s.png)
PHP实现数组根据某个字段进行水平合并,横向合并案例分析
2023-10-04 04:55:53
Python类的高级函数详解
2022-11-21 04:59:18
![](https://img.aspxhome.com/file/2023/9/103349_0s.jpg)
Python读取Word文档中的Excel嵌入文件的方法详解
2022-12-21 14:11:23
![](https://img.aspxhome.com/file/2023/8/80648_0s.png)
详解Python 中的容器 collections
2021-09-12 07:11:38
使用python的pexpect模块,实现远程免密登录的示例
2022-10-19 18:30:22
一文教你用Python中progress库实现进度条
2023-09-14 10:28:31
![](https://img.aspxhome.com/file/2023/5/101465_0s.gif)
Python3 Tkinkter + SQLite实现登录和注册界面
2023-10-01 14:56:15
![](https://img.aspxhome.com/file/2023/5/62945_0s.jpg)
通过实例学习Python Excel操作
2021-01-21 21:55:12
![](https://img.aspxhome.com/file/2023/2/78782_0s.png)
php隐藏IP地址后两位显示为星号的方法
2023-08-16 13:05:17
Python代码覆盖率统计工具coverage.py用法详解
2021-02-02 22:55:51
Python最大连续区间和动态规划
2023-02-13 09:40:32
![](https://img.aspxhome.com/file/2023/6/69516_0s.png)
网站制作流程及界面交互设计
2007-10-26 12:00:00
![](https://img.aspxhome.com/file/UploadPic/200710/26/2007102612842449s.jpg)
利用Python的Django框架生成PDF文件的教程
2023-07-15 14:26:04
简单获取键盘的KeyCode
2008-04-18 12:37:00
Caffe卷积神经网络视觉层Vision Layers及参数详解
2023-02-28 02:06:41
![](https://img.aspxhome.com/file/2023/5/84985_0s.png)
python文件选择对话框的操作方法
2023-08-02 16:27:21
![](https://img.aspxhome.com/file/2023/3/61193_0s.png)