使用命名空间使用Python从XML中提取数据

时间:2017-02-20 18:29:57

标签: python-3.x xml-parsing lxml

我正在尝试从日志中读取SOAP请求XML,并通过提取数据进行一些验证,但没有成功。

这是我想读的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>xxx@exxx.com</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)

1 个答案:

答案 0 :(得分:0)

最后这对我有用。但是如果有更好的解决方案,我想通过名称访问标签,这样我就不必循环

    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)