提取XML属性- python



我是Python新手& &;试图提取XML属性。下面是我尝试的代码。

import xml.etree.ElementTree as ET
a = '''<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<checkVatResponse xmlns="urn:ec.europa.eu:taxud:vies:services:checkVat:types">
<countryCode>RO</countryCode>
<vatNumber>43097749</vatNumber>
<requestDate>2022-07-12+02:00</requestDate>
<valid>true</valid>
<name>ROHLIG SUUS LOGISTICS ROMANIA S.R.L.</name>
<address>MUNICIPIUL  BUCUREŞTI, SECTOR 1
BLD. ION MIHALACHE Nr. 15-17
Et. 1</address>
</checkVatResponse>
</soap:Body>
</soap:Envelope>'''
tree = ET.ElementTree(ET.fromstring(a))
root = tree.getroot()
for cust in root.findall('Body/checkVatResponse'):
name = cust.find('name').text
print(name)

我想从XML中提取"名称"one_answers"地址"。但是当我运行上面的代码时,什么也没有打印出来。我错在哪里?

问候,玛雅潘德

名称空间狗,名称空间!可以肯定的是,当Jay-Z谈到有99个问题时,必须处理带有名称空间的XML绝对是其中之一!

参见使用名称空间解析XML

对于body标签,其命名空间为http://schemas.xmlsoap.org/soap/envelope/,checkVatResponse的命名空间为urn:ec.europa.eu:taxud:vies:services:checkVat:types,nameaddress的命名空间均为urn:ec.europa.eu:taxud:vies:services:checkVat:types,它们继承了父标签checkVatResponse

因此,您可以显式地搜索包含其名称空间的元素,如下所示:

root.findall('{http://schemas.xmlsoap.org/soap/envelope/}Body/{urn:ec.europa.eu:taxud:vies:services:checkVat:types}checkVatResponse')

或者你可以用通配符忽略它:

root.findall('{*}Body/{*}checkVatResponse')

试试这个:

a = '''<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<checkVatResponse xmlns="urn:ec.europa.eu:taxud:vies:services:checkVat:types">
<countryCode>RO</countryCode>
<vatNumber>43097749</vatNumber>
<requestDate>2022-07-12+02:00</requestDate>
<valid>true</valid>
<name>ROHLIG SUUS LOGISTICS ROMANIA S.R.L.</name>
<address>MUNICIPIUL  BUCUREŞTI, SECTOR 1
BLD. ION MIHALACHE Nr. 15-17
Et. 1</address>
</checkVatResponse>
</soap:Body>
</soap:Envelope>'''
tree = ET.ElementTree(ET.fromstring(a))
root = tree.getroot()
for cust in root.findall('{*}Body/{*}checkVatResponse'):
name = cust.find('{*}name').text
print(name)
address = cust.find('{*}address').text
print(address)
输出:

ROHLIG SUUS LOGISTICS ROMANIA S.R.L.
MUNICIPIUL  BUCUREŞTI, SECTOR 1
BLD. ION MIHALACHE Nr. 15-17
Et. 1

相关内容

  • 没有找到相关文章

最新更新