测试Python读写xml配置文件(续)

  除了xml.etree.ElementTree模块,Python还支持采用xml.dom.minidom读写xml文件,后者是文档对象模型接口的最小化实现,其目标是比完整 DOM 更简单并且更为小巧,但如果对于DOM 还不十分熟悉,则应考虑改用 xml.etree.ElementTree 模块来进行 XML 处理。
  读取xml文件时需要用到的对象及函数、属性如下,完整的代码及程序运行结果如下所示。从运行结果可以看出,xml.dom.minidom把元素的内容也作为一个节点,即#text,这点来说,没有xml.etree.ElementTree方便,后者不需要考虑这个。

序号函数或属性说明
1xml.dom.minidom.parse根据给定的输入返回Document对象,输入参数可以是文件名,也可以是文件类对象,如果xml内容保存在字符串中,可以使用parseString解析xml字符串
2Document.documentElement返回文档根元素
3Node.nodeName获取节点的节点名称,也即元素类型
4Node.nodeValue获取节点的值
5Node.attributes获取节点的属性集合
6Node.childNodes获取节点的子节点集合
7Node.hasAttributes获取节点是否有属性
8Node.hasChildNodes获取节点是否有子节点
9Attr.name节点属性的属性名称
10Attr.value节点属性的属性值
from xml.dom.minidom import parse

def ShowSubNode(curNode):
    print('节点:',curNode.nodeName,":",curNode.nodeValue)

    if curNode.nodeName=='#text':
        return

    if curNode.hasAttributes:
        for attr in curNode.attributes.values():
            print('属性:',attr.name,':',attr.value)       

    if curNode.hasChildNodes:
        for child in curNode.childNodes:
            ShowSubNode(child)
    

doc = parse('test.xml')
root = doc.documentElement
ShowSubNode(root)

在这里插入图片描述

  构建xml文件时需要用到的对象及函数、属性如下,完整的代码及程序运行结果如下所示:

序号函数或属性说明
1xml.dom.minidom.Document()创建新的文档对象
2Document.createElement新建元素节点
3Document.appendChild添加根节点
4Element.setAttribute新建节点属性,同时设置属性值
5Element.appendChild添加子节点
6Document.createTextNode创建文本节点
7Document.writexml保存xml到文件
import xml.dom.minidom

doc = xml.dom.minidom.Document()

root=doc.createElement("root")
root.setAttribute('ver','2.0')
doc.appendChild(root) 

classA=doc.createElement('classA')
root.appendChild(classA)
classA.setAttribute("master","张三")
classA.setAttribute("grade","一年级")
studentA=doc.createElement('studentA')
classA.appendChild(studentA)
studentA.appendChild(doc.createTextNode('小米'))

classB=doc.createElement('classB')
root.appendChild(classB)
classB.setAttribute("master","李四")
classB.setAttribute("grade","三年级")
studentB=doc.createElement('studentB')
classB.appendChild(studentB)
studentB.appendChild(doc.createTextNode('小明'))

with open("writetest1.xml", "w", encoding='utf-8') as f:
    doc.writexml(f, indent='\t', addindent='\t', newl='\n', encoding="utf-8")

在这里插入图片描述

  上述内容即为采用xml.dom.minidom读写xml文件的基本用法。测试代码主要参考自参考文献1-3,其中唯一需要说明的是枚举节点的属性集合,百度了很多文章都没有看到怎么枚举的,后面直接到xml.dom.minidom的源码中翻到的用法(参考文献4)。

参考文献:
[1]https://docs.python.org/zh-cn/3/library/xml.dom.minidom.html?highlight=xml%20dom%20minidom#module-xml.dom.minidom
[2]https://www.cnblogs.com/smart-zihan/p/12015192.html
[3]https://www.bootwiki.com/xmldom/dom-nodelist.html
[4]https://github.com/python/cpython/blob/3.10/Lib/xml/dom/minidom.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值