Python 使用lxml解析具有多个名称空间的xml
我从SOAP api中提取xml,如下所示:Python 使用lxml解析具有多个名称空间的xml,python,xpath,soap,lxml,Python,Xpath,Soap,Lxml,我从SOAP api中提取xml,如下所示: <SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ae="urn:sbmappservices72" xmlns:c14n="http://www.w3.org/2001/10/xml-exc-c14n#" xm
<SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ae="urn:sbmappservices72" xmlns:c14n="http://www.w3.org/2001/10/xml-exc-c14n#" xmlns:diag="urn:SerenaDiagnostics" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ae:GetItemsByQueryResponse>
<ae:return>
<ae:item>
<ae:id xsi:type="ae:ItemIdentifier">
<ae:displayName/>
<ae:id>10</ae:id>
<ae:uuid>a9b91034-8f4d-4043-b9b6-517ba4ed3a33</ae:uuid>
<ae:tableId>1541</ae:tableId>
<ae:tableIdItemId>1541:10</ae:tableIdItemId>
<ae:issueId/>
</ae:id>
但这似乎不起作用,因为当我尝试获取r的len时,它返回为0:
print 'length: ' + str(len(r)) #<---- always equals 0
print'length:'+str(len(r))#您的XPath与XML结构不正确对应。请尝试以下方法:
r = tree.xpath('/e:Envelope/e:Body/s:GetItemsByQueryResponse/s:return/s:item/s:id/s:tableId',
namespaces={'e': 'http://schemas.xmlsoap.org/soap/envelope/',
's': 'urn:sbmappservices72'})
对于小XML,您可能希望使用/
而不是/
来简化表达式,例如:
r = tree.xpath('/e:Envelope/e:Body//s:tableId',
namespaces={'e': 'http://schemas.xmlsoap.org/soap/envelope/',
's': 'urn:sbmappservices72'})
/e:Body//s:tableId
将找到tableId
,无论它嵌套在Body
中的深度有多深。但是请注意,/
肯定比/
慢,特别是在应用于大型XML时。其中一个名称空间是使用URN定义的这一事实并不重要。它和URL一样有效。谢谢,我也这么认为,但因为它不起作用,我不确定。如果可以,我会投你一票:]
r = tree.xpath('/e:Envelope/e:Body//s:tableId',
namespaces={'e': 'http://schemas.xmlsoap.org/soap/envelope/',
's': 'urn:sbmappservices72'})