如何从根中带有 xmlns 的 XML 文件中获取数据 [英] How to get data from an XML file with xmlns in root
本文介绍了如何从根中带有 xmlns 的 XML 文件中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编号.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>
数字.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.?
推荐答案
注意 XML 中没有前缀的 xmlns
声明了默认命名空间,没有前缀的后代元素继承默认命名空间从祖先隐含.现在要在命名空间中查找元素,您可以定义一个引用命名空间 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屋!
查看全文