简体   繁体   English

使用元素树解析 XML (Python)

[英]Using Element Tree to parse XML (Python)

I'm learning how to use ElementTree and I having some trouble parsing the XML as shown below.我正在学习如何使用 ElementTree,但在解析 XML 时遇到了一些问题,如下所示。 I ultimately would like to create a dictionary where the keys are the function id's and the values are a list of the callee id's (Ex. {'1': [20,22]}, {'3': [10,30,20,92]}) but I'm having trouble figuring out how to iterate through each function and access the id and callee attributes.我最终想创建一个字典,其中键是 function id,值是被调用者 id 的列表(例如 {'1': [20,22]}, {'3': [10,30, 20,92]}) 但我无法弄清楚如何遍历每个 function 并访问 id 和 callee 属性。 I've been trying to use findall() but I've been unsuccessful so I was wondering if I could get some help.我一直在尝试使用 findall() 但我没有成功,所以我想知道是否可以得到一些帮助。 Thanks!谢谢!

<?xml version="1.0" encoding="utf-8"?>
<myXML>
    <version>2</version>
    <functions>
        <function>
            <id>1</id>
            <callee>20</callee>
            <callee>22</callee>
        </function>
        <function>
            <id>3</id>
            <callee>10</callee>
            <callee>30</callee>
            <callee>20</callee>
            <callee>92</callee>
        </function>
    </functions>
</myXML>

Try something like this:尝试这样的事情:

import xml.etree.ElementTree as ET
calls = """[your xml above]"""
doc = ET.fromstring(calls)

calls_dict = {}
funcs = doc.findall('.//function')
for func in funcs:
    id = func.find('./id').text
    callees = [call.text for call in func.findall('.//callee')]
    calls_dict[id]=callees
for a,b in calls_dict.items():
    print(a,b)

Output: Output:

1 ['20', '22']
3 ['10', '30', '20', '92']

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

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