使用lxml解析具有多个名称空间的xml

时间:2015-07-22 21:19:17

标签: 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#" 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>

我不能为我的生活使用findall来拉取像tableId这样的东西。大多数使用lxml进行解析的教程都没有包含名称空间,但是the one at lxml.de确实如此,我一直在努力遵循它。

根据他们的教程,您应该创建一个名称空间的字典,我已经这样做了:

r = tree.xpath('/e:SOAP-ENV/s:ae', 
        namespaces={'e': 'http://schemas.xmlsoap.org/soap/envelope/',
                    's': 'urn:sbmappservices72'})

但是这似乎不起作用,因为当我试图获得r的len时,它回来为0:

print 'length: ' + str(len(r)) #<---- always equals 0

由于第二个命名空间的URI是“urn:”,我也尝试使用wsdl的真实URL,但这给了我相同的结果。

有什么明显的东西让我失踪吗?我只需要能够像tableIdItemId那样拉取值。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您的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时。