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。
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐