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

代码打印结果展示

相关推荐
橘颂TA3 分钟前
【Qt】项目的创建 and 各个控件的使用
开发语言·qt
Python×CATIA工业智造4 分钟前
Python索引-值对迭代完全指南:从基础到高性能系统设计
python·pycharm
我有一颗五叶草6 分钟前
线程间通信
java·开发语言
测试界清流6 分钟前
postman接口功能测试
开发语言·lua
Luchang-Li1 小时前
sglang pytorch NCCL hang分析
pytorch·python·nccl
一个天蝎座 白勺 程序猿6 小时前
Python爬虫(47)Python异步爬虫与K8S弹性伸缩:构建百万级并发数据采集引擎
爬虫·python·kubernetes
XiaoMu_0017 小时前
基于Django+Vue3+YOLO的智能气象检测系统
python·yolo·django
困到晕阙7 小时前
[NCTF2019]Fake XML cookbook
xml·xxe
honder试试8 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky8 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化