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

代码打印结果展示

相关推荐
AC赳赳老秦13 小时前
团队知识库搭建:用 OpenClaw 自动整理会议纪要、技术方案、故障复盘,同步到 Confluence / 语雀
开发语言·前端·python·github·visual studio·deepseek·openclaw
m0_6315298213 小时前
CSS如何利用Less快速生成颜色渐变背景_使用混合函数生成多样渐变
jvm·数据库·python
handler0113 小时前
算法:图的基本概念
c语言·开发语言·c++·笔记·算法·图论
m0_6245785913 小时前
Laravel Blade 中高效筛选并限制关联分类数据的实践方案
jvm·数据库·python
byzh_rc13 小时前
[AI工具从入门到入土] 命令行
网络·人工智能·python·深度学习·matplotlib
NEGl DRYN13 小时前
index.php 和 php
开发语言·php
m0_5913647314 小时前
golang如何实现coredump分析_golang coredump分析实现策略
jvm·数据库·python
玩代码的老秦14 小时前
后端php连接SQL Server数据库报错解决方案
开发语言·数据库·php
冰暮流星14 小时前
javascript之事件冒泡与事件捕获
开发语言·前端·javascript
财经资讯数据_灵砚智能14 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年5月1日
大数据·人工智能·python·信息可视化·自然语言处理