本文主要是介绍python中使用xml.dom.minidom模块读取解析xml文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
python中可以使用xml.dom.minidom模块读取解析xml文件
xml.dom.minidom模块应该是内置模块不用下载安装
对于一个xml文件来说比如这个xml文件的内容为如下
<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>
代码如下
from xml.dom import minidomdoc = 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("==========================")
代码打印结果展示
这篇关于python中使用xml.dom.minidom模块读取解析xml文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!