How to get data from an XML file with xmlns in root

核能气质少年 提交于 2020-01-09 05:33:11

问题


number.xml

<?xml version="1.0" encoding="utf-8"?>
<ResponseSent>
  <ResponseDate xmlns="http://example.com/schema">
   <emailid>123@test.com</emailid>
    <number>22</number>
    <sent>2017-12-05</sent>
 </ResponseDate>

number.py

import xml.etree.ElementTree as ET
tree = ET.parse('number.xml')
root = tree.getroot()
for country in root.findall('ResponseDate'):
    rank = country.find('emailid').text
    name = country.find('number').text
    print(name, rank)

Returning empty results, but when I modify the xml to name= instead of xmlns= then it is working. But, how to make this script work with the xmlns.?


回答1:


Notice that xmlns without prefix in XML declares default namespace, and descendants element without prefix inherit default namespace from ancestor implicitly. Now to find element in namespace you can define a prefix that references the namespace URI, and use combination of that prefix and target element's local name :

....
ns = { 'd': 'http://example.com/schema' }
for country in root.findall('d:ResponseDate', ns):
    rank = country.find('d:emailid', ns).text
    name = country.find('d:number', ns).text
    print(name, rank)


来源:https://stackoverflow.com/questions/48675421/how-to-get-data-from-an-xml-file-with-xmlns-in-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!