首页 > 解决方案 > 解析命名空间 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”对象没有属性“文本”

任何方向都会有所帮助

标签: pythonxml-parsinglxmlxml-namespaces

解决方案


它应该与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

推荐阅读