您当前的位置: 首页 >  Python

Xavier Jiezou

暂无认证

  • 2浏览

    0关注

    394博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Python】基于 DOM 的 XML 文档写入(xml.dom.minidom)

Xavier Jiezou 发布时间:2021-08-12 17:06:56 ,浏览量:2

引言

本文讲解如何利用 Python 内置模块 xml.dom.minidom 快速完成 xml 文档写入工作。

示例


	
	hello world
	Xavier Jiezou
	
		
			Jack
			18
			male
		
		
			John
			19
			male
		
		
			jane
			20
			female
		
	

代码
from xml.dom import minidom


def create_xml_minidom(save_name):
    # 新建 xml 文档对象
    doc = minidom.Document()

    # 创建根节点
    root = doc.createElement('root')
    # 设置根节点属性
    root.setAttribute('csdn', 'https://blog.csdn.net/qq_42951560')
    # 添加根节点到文档对象
    doc.appendChild(root)

    # 创建注释节点
    comment = doc.createComment("Xavier's Profile")
    root.appendChild(comment)

    # 创建文本节点
    text = doc.createTextNode('hello world')
    root.appendChild(text)

    # 创建第一个叶子节点
    name = doc.createElement('name')
    name.appendChild(doc.createTextNode('Xavier Jiezou'))
    root.appendChild(name)

    # 创建第二个叶子节点
    friends = doc.createElement('firends')
    friends_list = [
        {'name': 'Jack', 'age': 18, 'gender': 'male'},
        {'name': 'John', 'age': 19, 'gender': 'male'},
        {'name': 'jane', 'age': 20, 'gender': 'female'}
    ]
    for item in friends_list:
        friend = doc.createElement('friend')
        name = doc.createElement('name')
        name.appendChild(doc.createTextNode(item['name']))
        age = doc.createElement('age')
        age.appendChild(doc.createTextNode(str(item['age'])))
        gender = doc.createElement('gender')
        gender.appendChild(doc.createTextNode(item['gender']))
        friend.appendChild(name)
        friend.appendChild(age)
        friend.appendChild(gender)
        friends.appendChild(friend)
    root.appendChild(friends)

    # 保存 xml 文档对象
    with open(save_name, 'wb') as f:
        f.write(doc.toprettyxml(encoding='utf-8'))


if __name__ == '__main__':
    create_xml_minidom('text.xml')
推荐

【Python】基于 DOM 的 XML 文档解析(xml.dom.minidom)

参考

https://docs.python.org/3/library/xml.dom.html

关注
打赏
1661408149
查看更多评论
立即登录/注册

微信扫码登录

0.0382s