Python xml 读取操作之 xml.dom 模块
Python xml 读取操作之 xml.dom 模块
最近工作中需要从xml中提取数据作对比,android的manifest.xml的根节点是比较复杂的,如何精准的定位到想定位的子节点并且提取该子节点的节点名称、属性呢?这个问题弄得我烦恼好久,终于屡清楚了,写此文做个例子,希望可以帮助到大家。
先来了先导,介绍下关于 xml 读取用到的基本操作:
minidom.parse(filename) # 加载读取XML文件
doc.documentElement # 获取XML文档对象
node.getAttribute(AttributeName) # 获取XML节点属性值
node.getElementsByTagName(TagName) # 获取XML节点对象集合
node.childNodes # 返回子节点列表
node.childNodes[index].nodeValue # 获取XML节点值
node.nodeName # 获取当前节点tag名称
node.firstChild # 访问第一个节点。等价于pagexml.childNodes[0]
下面我们实操以下,如下是一份简易的 androidmanifes.xml 文件,我们就以它为例子进行练习:
本次操作我最实用的方法如下:
xmldom = xml.dom.minidom.parse(xml_path) # 加载XML
xmlroot = xmldom.documentElement # 获取XML对象
xmlroot.getElementsByTagName(‘uuppii’) # 返回 list
node.getAttribute(‘xxyyzz’) # 返回 string
node.childNodes # 返回 list
node.nodeName # 返回 string
<?xml version="1.0" encoding="utf-8" standalone="no"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.huahua.miaomiao" platformBuildVersionCode="26" platformBuildVersionName="0.0.0">
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:xlargeScreens="true"/>
<permission android:name="com.huahua.miaomiao.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses