繁体   English   中英

用 python 解析 XML 数据 - 如何以更 Pythonic 的方式捕获所有内容?

[英]Parsing XML data with python - how to capture everything in a more pythonic way?

目的是捕获 xml 文件中的所有数据。 捕获后,我将其与参考 xml 文件进行比较,以确保没有任何变化,然后告诉您有什么不同。

我写的东西可以满足我的需要,但是很麻烦而且有点乱? 有没有更好的方法来遍历 xml 文件所有深度的所有项目。 该解决方案必须是强大的以捕获所有内容。

目前,像我在下面使用的迭代也可以使用 try/except 进行迭代层,这非常难看!

import xml.etree.ElementTree as ET

def xml_iter(file):
    
    tree = ET.parse(file)
    root = tree.getroot()
    
    namespaces = {}

    List = []
    Parent = []
    for elem in root:
        for i in elem:
            try:
                i = i.text.strip()
                List.append(i)
            except:
                pass
     
            for j in i:
                try:
                    j = j.text.strip()
                    List.append(j)
                except:
                    pass
  
                for k in j:
                    try:
                        k = k.text.strip()
                        List.append(k)
                    except:
                        pass
    return (List)

任何帮助将不胜感激。

用户元素.iter 它递归地遍历所有子树。

对于您的情况,它将类似于:

dict_list = []
text_list = []
for node in root.iter():
    dict_list.append(node.attrib) # adds to list, the dictionary of attrib
    text_list.append(node.text)

 

# do the same for other file and compare dictionaries/strings in corresponding lists.

您可以查看此官方教程以获取示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM