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

代码打印结果展示

相关推荐
小鸡吃米…1 分钟前
Python 网络爬虫 —— 环境设置
开发语言·爬虫·python
add45a11 分钟前
C++中的观察者模式
开发语言·c++·算法
sw12138912 分钟前
Python字典与集合:高效数据管理的艺术
jvm·数据库·python
进击的小头15 分钟前
第13篇:基于伯德图的超前_滞后校正器深度设计
python·算法
该怎么办呢21 分钟前
Source/Core/Event.js
开发语言·javascript·ecmascript·cesium
似水明俊德22 分钟前
04-C#.Net-委托和事件-面试题
java·开发语言·面试·c#·.net
johnrui38 分钟前
集合与树形结构
开发语言·windows
m0_7380980243 分钟前
使用Python操作文件和目录(os, pathlib, shutil)
jvm·数据库·python
好家伙VCC1 小时前
# 发散创新:用 Rust构建高性能游戏日系统,从零实现事件驱动架构 在现代游戏开发中,**性能与可扩展性**是核心命题。传统基于
java·python·游戏·架构·rust