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

代码打印结果展示

相关推荐
zzb15807 分钟前
Zed 配置 Swift / iOS 开发
开发语言·ios·swift
盼小辉丶10 分钟前
OpenCV-Python实战(33)——构建实时目标检测与跟踪系统
python·opencv·目标检测·计算机视觉
bill32822780431 小时前
从 0 到 1 掌握 1688API:商品详情获取技巧
python
北冥you鱼2 小时前
Go-Ethereum (Geth) 最佳实践:从部署到生产环境优化
开发语言·后端·golang
这不小天嘛9 小时前
JAVA八股——J集合篇
java·开发语言
hboot9 小时前
AI工程师第五课 - 大语言模型基础
python·llm·fastapi
AOwhisky9 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发
STLearner10 小时前
ICML 2026 | LLM×Graph论文总结[1]【图基础模型,文本属性图,多模态属性图,图对齐,图提示学习,关系深度学习
论文阅读·人工智能·python·深度学习·学习·机器学习·数据挖掘
习明然11 小时前
我的本地化AI项目(三)
人工智能·python·electron·c#·avalonia
喜欢的名字被抢了12 小时前
Python实战:SQLAlchemy ORM与FastAPI项目集成
开发语言·python·sql·教程·fastapi