ElementTree 错误:“xml.etree.ElementTree.Element”对象没有属性“root”

问题描述 投票:0回答:1

我是 XML 新手,一直在努力理解如何从 API 调用中解压以下 xml 响应。

我尝试过使用 import xml.etree.ElementTree 但没有运气。大多数教程都是从加载根开始的,但是当我尝试这样做时,我得到以下信息

AttributeError:'xml.etree.ElementTree.Element'对象没有属性'root'

import requests
import xml.etree.ElementTree as et

Data = apiCall()
tree = et.fromstring(Data.content)


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <DoLoginResponse xmlns="http://endpoint.com/">
            <DoLoginResult>
                <OperationStatus>true</OperationStatus>
                <StatusMessage />
                <SecurityProfile>
                    <User>
                        <UserID>101</UserID>
                        <UserName>test</UserName>
                    </User>
                    <Session>
                        <SessionId>000000</SessionId>
                    </Session>
                    <IsFirstLogon>true</IsFirstLogon>
                    <IsSystemOwner>false</IsSystemOwner>
                </SecurityProfile>
            </DoLoginResult>
        </DoLoginResponse>
    </soap:Body>
</soap:Envelope>
python xml python-requests elementtree
1个回答
0
投票

fromstring
希望您的数据采用
str
或 ReadableBuffer 格式。 而且,如果您使用
fromString
,您将
Element
对象作为返回值。因此您将无法访问
root
属性。因此,如果您想使用
getroot()
方法从 xml 获取 root,则可以这样做。

import xml.etree.ElementTree as ET
tree = ET.parse('you_data.xml')
root = tree.getroot()
© www.soinside.com 2019 - 2024. All rights reserved.