Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

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

number.xml

<?xml version="1.0" encoding="utf-8"?>
<ResponseSent>
  <ResponseDate xmlns="http://example.com/schema">
   <emailid>[email protected]</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.?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...