python中使用xml.dom.minidom模块读取解析xml文件

python中可以使用xml.dom.minidom模块读取解析xml文件

xml.dom.minidom模块应该是内置模块不用下载安装

对于一个xml文件来说比如这个xml文件的内容为如下

html 复制代码
<excel version="1.0" author="huangzhihui">
    <table id="1">
        <colum id="1.1" name="Mike1" width="1" height="1" />
        <colum id="1.2" name="John1" width="2" height="2" />
        <colum id="1.3" name="Lucy1" width="3" height="3" />
    </table>
    <table id="2">
        <colum id="2.1" name="Mike1" width="1" height="1" />
        <colum id="2.2" name="John1" width="2" height="2" />
        <colum id="2.3" name="Lucy1" width="3" height="3" />
    </table>
</excel>

代码如下

bash 复制代码
from xml.dom import minidom

doc = minidom.parse(r'C:\Users\xxxxxxx\Desktop\test.xml')  #解析xml文件(句柄或文件路径)
#doc = minidom.parseString()  #解析xml字符串
root_node = doc.documentElement  #获得根节点对象
xml_excel_obj_list = root_node.getElementsByTagName('excel')
print(xml_excel_obj_list)

xml_table_obj_list = root_node.getElementsByTagName('table')
print(xml_table_obj_list)

for table in xml_table_obj_list:
    print("==========================")
    lines_obj_list = table.getElementsByTagName('colum')
    for line_obj in lines_obj_list:
        print(line_obj.getAttribute("name"), line_obj.getAttribute("width"), line_obj.getAttribute("height"))
    print("==========================")

代码打印结果展示

相关推荐
0wioiw013 分钟前
Python基础(Flask①)
后端·python·flask
我是哈哈hh14 分钟前
【Node.js】ECMAScript标准 以及 npm安装
开发语言·前端·javascript·node.js
飞翔的佩奇33 分钟前
【完整源码+数据集+部署教程】食品分类与实例分割系统源码和数据集:改进yolo11-AggregatedAttention
python·yolo·计算机视觉·数据集·yolo11·食品分类与实例分割
OperateCode1 小时前
AutoVideoMerge:让二刷更沉浸的自动化视频处理脚本工具
python·opencv·ffmpeg
蔡俊锋1 小时前
Javar如何用RabbitMQ订单超时处理
java·python·rabbitmq·ruby
跟橙姐学代码1 小时前
学Python别死记硬背,这份“编程生活化笔记”让你少走三年弯路
前端·python
Sammyyyyy2 小时前
2025年,Javascript后端应该用 Bun、Node.js 还是 Deno?
开发语言·javascript·node.js
站大爷IP2 小时前
Python与MySQL:从基础操作到实战技巧的完整指南
python
老歌老听老掉牙2 小时前
SymPy 矩阵到 NumPy 数组的全面转换指南
python·线性代数·矩阵·numpy·sympy
站大爷IP2 小时前
Python条件判断:从基础到进阶的实用指南
python