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("==========================")

代码打印结果展示

相关推荐
【ql君】qlexcel27 分钟前
Notepad++ 复制宏、编辑宏的方法
开发语言·javascript·notepad++··宏编辑·宏复制
Zevalin爱灰灰36 分钟前
MATLAB GUI界面设计 第六章——常用库中的其它组件
开发语言·ui·matlab
冰糖猕猴桃43 分钟前
【Python】进阶 - 数据结构与算法
开发语言·数据结构·python·算法·时间复杂度、空间复杂度·树、二叉树·堆、图
天水幼麟1 小时前
python学习笔记(深度学习)
笔记·python·学习
巴里巴气1 小时前
安装GPU版本的Pytorch
人工智能·pytorch·python
wt_cs1 小时前
银行回单ocr api集成解析-图像文字识别-文字识别技术
开发语言·python
_WndProc2 小时前
【Python】Flask网页
开发语言·python·flask
互联网搬砖老肖2 小时前
Python 中如何使用 Conda 管理版本和创建 Django 项目
python·django·conda
测试者家园2 小时前
基于DeepSeek和crewAI构建测试用例脚本生成器
人工智能·python·测试用例·智能体·智能化测试·crewai
liujing102329292 小时前
Day04_刷题niuke20250703
java·开发语言·算法