2016-01-21 142 views
1

我有一個XML字符串,我需要解析蟒,看起來像這樣:如何解析分層XML字符串

<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() 

回答

2

使用部分XPath support

ET.fromstring(text).find('.//{http://schemas.datacontract.org/2004/07/WebServices}ErrorMessage') 

這將指示它找到網絡第一個名稱爲ErrorMessage的元素,其名稱空間爲http://schemas.datacontract.org/2004/07/WebServices

但是,它可能會更快使用類似

ET.fromstring(text).find('{http://schemas.xmlsoap.org/soap/envelope/}Body').find('{http://webservices.truckstop.com/v11}PostLoadsResponse').find('{http://webservices.truckstop.com/v11}PostLoadsResult').find('{http://schemas.datacontract.org/2004/07/WebServices}Errors').find('{http://schemas.datacontract.org/2004/07/WebServices}Error').find('{http://schemas.datacontract.org/2004/07/WebServices}ErrorMessage' 

如果你知道你的消息總是包含這些元素。

5

你需要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) 

打印Invalid Location

2

您可以使用樹上的getiterator方法遍歷其中的項目。你可以檢查每個項目上的tag,看它是否是正確的。

>>> err = [node.text for node in tree.getiterator() if node.tag.endswith('ErrorMessage')] 
>>> err 
['Invalid Location']