python - 解析命名空间 XML 的问题。显示为空。在 Python 中
问题描述
我的 XML 文件可在此处获得。虽然我能够从此文件中获取根节点及其子节点。但是,我无法得到我需要的那个。我想获取 <ce:section-title>Methods</ce:section-title>
我已经尝试过 xml 和 lxml 包的内容。
当我使用以下内容时,
tree = lxml.etree.parse(fname) #fname is xml filename
root= tree.getroot()
print(root[5].findall("ce:section-title",root.nsmap)
它只是给了我 null [] 括号。当我使用以下命令时,它给出了相同的空括号:
for item in tree.iter('{http://www.elsevier.com/xml/ja/dtd}ce:section-title'):
print(item)
我确实尝试使用此处提供的解决方案来解决,但我在此代码上收到以下错误:
ns = {"ce":"http://www.elsevier.com/xml/common/dtd"}
print(root.findall("ce:title", ns).text)
AttributeError:“NoneType”对象没有属性“文本”
任何方向都会有所帮助
解决方案
它应该与findall(.//ce:section-title, root.nsmap)
.
使用.//
前置,您正在搜索section-title
上下文节点下所有级别的后代。使用findall(ce:section-title, root.nsmap)
,只能定位直接子元素。
例子:
from lxml import etree
tree = etree.parse("data.xml") # Your XML
root = tree.getroot()
for e in root.findall(".//ce:section-title", root.nsmap):
print(e.text)
输出:
Abstract
Keywords
Introduction
Materials and methods
Results
The appearing species by taxon
List of regional appearing species
Discussion
Acknowledgments
References
推荐阅读
- c# - ASP.NET 使用按钮调用视图中的方法
- python - 如何组合具有不同行大小的两个数据框?
- c# - 如何从 3 位 ISO 国家代码中获取 3 位/字母货币代码
- flutter - itemBulder 跳转到下一项
- linux - 我们能否 mmap /dev/mem 为容器内的 dmidecode 提供预期输出
- c# - 实体框架 DbContext 和延迟加载
- javascript - 加载并显示有条件的数据,但不满足条件
- c# - 如何使用 AutoMapper 中的自定义逻辑从其他属性映射属性?
- android - 如何在材质按钮的一侧添加边框颜色?
- python - Airflow KubernetesExecutor 调度程序 kube watch 进程死亡