python 用元素树从xml中获取信息

umuewwlo  于 2023-05-27  发布在  Python
关注(0)|答案(1)|浏览(157)

我尝试使用elementTree来获取xml响应中的信息。
响应xmlresponse.xml看起来像:

<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://somewhere.co.uk/">
    <count>1</count>
    <pageInformation>
        <offset>0</offset>
        <size>10</size>
    </pageInformation>
    <items>
        <person uuid="1">
            <name>
                <firstName>John</firstName>
                <lastName>Doe</lastName>
            </name>
            <ManagedByRelations>
                <managedByRelation Id="1234">
                    <manager uuid="2">
                        <name formatted="false">
                            <text>Jane Doe</text>
                        </name>
                    </manager>
                    <managementPercentage>30</managementPercentage>
                    <period>
                        <startDate>2019-09-26</startDate>
                    </period>

                </managedByRelation>
                <managedByRelation Id="1234">
                    <manager uuid="3">
                        <name formatted="false">
                            <text>Joe Bloggs</text>
                        </name>
                    </manager>
                    <managementPercentage>70</managementPercentage>
                    <period>
                        <startDate>2019-09-26</startDate>
                    </period>
                </managedByRelation>
            </ManagedByRelations>
            <fte>0.0</fte>
        </person>
    </items>
</result>

如何使用elementTree获取包含的信息,例如,如何检索经理姓名、ID和开始日期的列表?
如果我这样做:

from xml.etree.ElementTree import Element, ParseError, fromstring, tostring, parse

tree = parse('xmlresponse.xml')
root = tree.getroot()

for manager in root.findall('managedByRelation'):
    print(manager)

findall()不返回任何东西。我知道我可以做一个list(root.iter())来遍历树中的所有内容,但是我想知道为什么root.findall()没有像我期望的那样工作?

bwntbbo3

bwntbbo31#

你可以iter()到find分支中:

import xml.etree.ElementTree as ET

tree = ET.parse('xmlresponse.xml')
root = tree.getroot()

for manRel in root.findall('.//managedByRelation'):
    for manager in manRel.iter('manager'):
        uuid = manager.get('uuid')
    for name in manRel.iter('text'):
        full_name = name.text
    for managementPercentage in manRel.iter('managementPercentage'):
        managementPercentage = managementPercentage.text
    for startdate in manRel.iter('startDate'):
        date = startdate.text
    print(f"{uuid} {full_name:^20} {managementPercentage:^10} {date}")

输出:

2       Jane Doe           30     2019-09-26
3      Joe Bloggs          70     2019-09-26

相关问题