如何从 root 中带有 xmlns 的 XML 文件中获取数据
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>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)
返回空结果,但是当我将 xml 修改为 name= 而不是 xmlns= 时,它正在工作。但是,如何使这个脚本与 xmlns.?
一起工作
请注意 XML 中不带前缀的 xmlns
声明了 默认命名空间 ,并且不带前缀的后代元素隐式继承了祖先的默认命名空间。现在要在命名空间中查找元素,您可以
定义引用命名空间 URI 的前缀,并使用该前缀和目标元素的本地名称的组合:
....
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)
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)
返回空结果,但是当我将 xml 修改为 name= 而不是 xmlns= 时,它正在工作。但是,如何使这个脚本与 xmlns.?
一起工作请注意 XML 中不带前缀的 xmlns
声明了 默认命名空间 ,并且不带前缀的后代元素隐式继承了祖先的默认命名空间。现在要在命名空间中查找元素,您可以
定义引用命名空间 URI 的前缀,并使用该前缀和目标元素的本地名称的组合:
....
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)