Skip to main content
 首页 » 编程设计

python之如何解析分层的 XML 字符串

2025年05月04日13duanxz

我有一个 xml 字符串需要在 python 中解析,如下所示:

 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
     <s:Body> 
         <PostLoadsResponse xmlns="http://webservices.truckstop.com/v11"> 
             <PostLoadsResult xmlns:a="http://schemas.datacontract.org/2004/07/WebServices.Objects" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
                 <Errors xmlns="http://schemas.datacontract.org/2004/07/WebServices"> 
                    <Error> 
                         <ErrorMessage>Invalid Location</ErrorMessage> 
                    </Error> 
                </Errors> 
            </PostLoadsResult> 
        </PostLoadsResponse> 
    </s:Body> 
</s:Envelope>' 

我在使用 xmltree 获取此树的错误消息时遇到问题,没有类似的内容:

import xml.etree.ElementTree as ET 
ET.fromstring(text).findall('{http://schemas.xmlsoap.org/soap/envelope/}Body')[0].getchildren()[0].getchildren()[0].getchildren() 

请您参考如下方法:

您需要handle namespaces你可以用 xml.etree.ElementTree 来做到这一点:

tree = ET.fromstring(data) 
 
namespaces = { 
    's': 'http://schemas.xmlsoap.org/soap/envelope/',  
    'd': "http://schemas.datacontract.org/2004/07/WebServices" 
} 
print(tree.find(".//d:ErrorMessage", namespaces=namespaces).text) 

打印无效位置。