2017-02-20 85 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