问题
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