2017-02-20 41 views
0

我想從日誌中讀取SOAP請求XML,並通過提取數據來做一些驗證但沒有成功。使用Python從名稱空間中使用Python提取數據

這裏是我嘗試讀取XML:

<?xml version="1.0" encoding="UTF-8"?> 
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<soapenv:Body> 
    <createOrder xmlns="http://services.xxx.xxx.xxx.com"> 
    <createOrderRequest> 
    <ns1:order xmlns:ns1="http://beans.xxx.xxx.xxx.com/xsd"> 
    <ns1:customer> 
     <ns1:billingAddress> 
     <ns1:addressLine1>my home address</ns1:addressLine1> 
     <ns1:addressLine2></ns1:addressLine2> 
     <ns1:addressType>B</ns1:addressType> 
     <ns1:city>cityofmine</ns1:city> 
     <ns1:countryCode>countrycode</ns1:countryCode> 
     <ns1:firstName>Jo</ns1:firstName> 
     <ns1:lastName>Sm</ns1:lastName> 
     <ns1:state>IL</ns1:state> 
     <ns1:zipCode>60135</ns1:zipCode> 
     </ns1:billingAddress> 
     <ns1:customerReferenceId>[email protected]</ns1:customerReferenceId> 
    </ns1:customer> 
    <ns1:items> 
     <ns1:addressKey>99999</ns1:addressKey> 
     <ns1:orderItemId>xxxxx1231</ns1:orderItemId> 
    </ns1:items> 
    </ns1:order> 
    </createOrderRequest> 
    </createOrder> 
    </soapenv:Body> 
</soapenv:Envelope> 

這裏是我與努力的代碼,但我無法找到的元素。

import xml.etree.ElementTree as ET 

def read_create_order(): 
    tree = ET.parse('create_ord.xml') 
    root = tree.getroot() 
    print(root.tag) 
    name_space = {'ns1':'http://beans.xxx.xxx.xxx.com/xsd'} 
    for item in tree.findall('items', namespaces=name_space): 
     print(item) 
    for item in root.findall('items', namespaces=name_space): 
     print(item) 

回答

0

最後這個工作了me.But如果有什麼更好的解決方案,我想通過名稱來訪問標籤,這樣我就不必循環

ns = etree.FunctionNamespace('http://beans.xxx.xxx.xxx.com/xsd') 
    ns.prefix = "ns1" 
    ldoc = etree.parse('create_ord.xml') 
    for sub_elements in ldoc.xpath('.//ns1:order/ns1:customer/ns1:billingAddress'): 
    for element in sub_elements: 
     print(element.text) 
+1

*「我想通過名稱訪問標籤,以便我不必循環「*,您試圖訪問哪個特定標籤? – mzjn

+0

@mzjn我現在可以通過這種方式訪問​​特定字段'ldoc.xpath('.// ns1:order/ns1:customer')'。但我確切的意思是......在上面的示例代碼中,對於ldoc.xpath中的sub_elements('.// ns1:order/ns1:customer/ns1:billingAddress'):'一旦我在'billingAddress'的父節點中,我想知道如果我可以做'.get('ns1addressLine2')'' – VBJ