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

代码打印结果展示

相关推荐
864记忆几秒前
Qt Sql 模块中的函数详解
开发语言·网络·qt
是店小二呀11 分钟前
五分钟理解Rust的核心概念:所有权Rust
开发语言·后端·rust
她说人狗殊途13 分钟前
存储引擎MySQL
开发语言
自然数e19 分钟前
C++多线程【线程管控】之线程转移以及线程数量和ID
开发语言·c++·算法·多线程
Arva .21 分钟前
ConcurrentHashMap 的线程安全实现
java·开发语言
Dxy123931021633 分钟前
Python为什么要使用可迭代对象
开发语言·python
Keep_Trying_Go1 小时前
论文STEERER人群计数,车辆计数以及农作物计数算法详解(pytorch)
人工智能·pytorch·python
gzu_011 小时前
基于昇腾 配置pytorch环境
人工智能·pytorch·python
任子菲阳1 小时前
学Java第四十五天——斗地主小游戏创作
java·开发语言·windows
前进的李工1 小时前
LeetCode hot100:234 回文链表:快慢指针巧判回文链表
python·算法·leetcode·链表·快慢指针·回文链表