Python xml 读取之 ET.parse
前一篇写到了xml 读取方法(一)dom.minidom,本次再介绍一种方法:ET.parse。
常用操作:
tree = ET.parse(xml_path)
root = tree.getroot() # 获取根节点
node.tag # 获取节点名字,string
node…attrib # 获取节点全部属性,dict
要想遍历某一层节点下的子节点,貌似只可以一层一层,从根节点开始,慢慢遍历:
xml文件用上一篇的xml即可,写了小段实际操作代码 如下:
def xml_read(content):
tree = ET.parse('../../../../androidmanifest.xml')
root = tree.getroot()
for child in root:
if child.tag == 'application':
for child1 in child:
if child1.tag == 'activity':
for key, value in child1.attrib.items():
if value == content:
str_tag = ''
str_attrib = ''
for inter_child in child1:
if inter_child.tag == 'intent-filter':
for child2 in inter_child:
str_tag += child2.tag + '|'
for key, value in child2.attrib.items():
str_attrib += value + '|'
if 'action' in str_tag and 'category' in str_tag and len(inter_child) == 2 and 'android.intent.action.MAIN' in str_attrib and 'android.intent.category.LAUNCHER' in str_attrib:
return True
else:
return False
代码的主要意思就是:
1.先通过根节点获取application节点,再在application中遍历tag名称为activity的标签
2.获取activity节点的属性,,若其中有和content相同的话,那么我们继续遍历activity节下的子节点(跳到步骤3),如果没有和content相同的话,就不用理会;
3. 先判断有没有intent-filter节点,没有则后面判读会失败,如果有,则继续遍历intent-filter下所有节点中是不是有action和category,如果有,则继续判断这两个标签的属性值,是不是和下面的if条件中符合,符合则返回结果为true,不符合或者没有action\category其中任意一个子节点的话,都是返回false。