如何从根为xmlns的XML文件中获取数据 [英] How to get data from an XML file with xmlns in root
问题描述
number.xml
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
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一起使用??
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.?
推荐答案
请注意 xmlns $ XML中不带前缀的c $ c>声明了默认名称空间,而没有前缀的后代元素从祖先隐式继承了默认名称空间。现在要在命名空间中查找元素,您可以
定义一个引用命名空间URI的前缀,并使用该前缀和目标元素的本地名称的组合:
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)
这篇关于如何从根为xmlns的XML文件中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!