如何使用python xml.etree.ElementTree通过正确的xpath获取值
这是'soap.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:Header>
<platformMsgs:documentInfo xmlns:platformMsgs="urn:messages_2014_1.platform.webservices.netsuite.com">
<platformMsgs:nsId>WEBSERVICES_3883026_SB1_103120188552030381995151284_f039e9cc</platformMsgs:nsId>
</platformMsgs:documentInfo>
</soapenv:Header>
<soapenv:Body>
<searchResponse xmlns="urn:messages_2014_1.platform.webservices.netsuite.com">
<platformCore:searchResult xmlns:platformCore="urn:core_2014_1.platform.webservices.netsuite.com">
<platformCore:status isSuccess="true"/>
<platformCore:totalRecords>200</platformCore:totalRecords>
<platformCore:pageSize>1000</platformCore:pageSize>
<platformCore:totalPages>1</platformCore:totalPages>
<platformCore:pageIndex>1</platformCore:pageIndex>
<platformCore:searchId>WEBSERVICES_3883026_SB1_103120188552030381995151284_f039e9cc</platformCore:searchId>
</platformCore:searchResult>
</searchResponse>
</soapenv:Body>
</soapenv:Envelope>
这是我的代码。
import xml.etree.ElementTree as ET
tree = ET.parse('soap.xml')
print tree.findall('.//{http://schemas.xmlsoap.org/soap/envelope/}platformCore')
但是它返回[]而不是value ='200'
答案 0 :(得分:0)
您需要使用正确的名称空间(nsmap),然后可以使用前缀轻松进行搜索:
from lxml import etree
tree = etree.parse('soap.xml')
nsmap = {'platformCore': 'urn:core_2014_1.platform.webservices.netsuite.com'}
print (tree.findall('.//platformCore:totalRecords', nsmap)[0].text)
返回:
200