除了xml.etree.ElementTree模块,Python还支持采用xml.dom.minidom读写xml文件,后者是文档对象模型接口的最小化实现,其目标是比完整 DOM 更简单并且更为小巧,但如果对于DOM 还不十分熟悉,则应考虑改用 xml.etree.ElementTree 模块来进行 XML 处理。
读取xml文件时需要用到的对象及函数、属性如下,完整的代码及程序运行结果如下所示。从运行结果可以看出,xml.dom.minidom把元素的内容也作为一个节点,即#text,这点来说,没有xml.etree.ElementTree方便,后者不需要考虑这个。
| 序号 | 函数或属性 | 说明 |
|---|---|---|
| 1 | xml.dom.minidom.parse | 根据给定的输入返回Document对象,输入参数可以是文件名,也可以是文件类对象,如果xml内容保存在字符串中,可以使用parseString解析xml字符串 |
| 2 | Document.documentElement | 返回文档根元素 |
| 3 | Node.nodeName | 获取节点的节点名称,也即元素类型 |
| 4 | Node.nodeValue | 获取节点的值 |
| 5 | Node.attributes | 获取节点的属性集合 |
| 6 | Node.childNodes | 获取节点的子节点集合 |
| 7 | Node.hasAttributes | 获取节点是否有属性 |
| 8 | Node.hasChildNodes | 获取节点是否有子节点 |
| 9 | Attr.name | 节点属性的属性名称 |
| 10 | Attr.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文件时需要用到的对象及函数、属性如下,完整的代码及程序运行结果如下所示:
| 序号 | 函数或属性 | 说明 |
|---|---|---|
| 1 | xml.dom.minidom.Document() | 创建新的文档对象 |
| 2 | Document.createElement | 新建元素节点 |
| 3 | Document.appendChild | 添加根节点 |
| 4 | Element.setAttribute | 新建节点属性,同时设置属性值 |
| 5 | Element.appendChild | 添加子节点 |
| 6 | Document.createTextNode | 创建文本节点 |
| 7 | Document.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