首页 > 解决方案 > 在 Python 中使用命名空间从 XML 节点检索属性

问题描述

我知道已经有一些从 XML 节点检索特定属性的示例,但是我没有成功地使用名称空间这样做。我能够检索没有任何命名空间的属性,例如在这个例子中。

假设我有以下“example.wsdl”文件:

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" name="Name of the file">
  <wsdl:documentation>Documentation of the file</wsdl:documentation>
</wsdl:definitions>

我想检索节点“wsdl:defintions”的“名称”属性,我尝试执行以下操作:

from lxml import etree

tree = etree.parse("example.wsdl")
rootWSDL = tree.getroot()

print(tree.find('./wsdl:definitions', rootWSDL.nsmap).attrib['name'])

但是,上面返回了一个空列表,其中包含以下消息:

AttributeError:“NoneType”对象没有属性“attrib”

对于它的价值,我使用的 Python 版本是 3.7.5

标签: pythonpython-3.xxmlwsdl

解决方案


您可以直接从根目录访问它。

前任:

from lxml import etree

tree = etree.parse("example.wsdl")
rootWSDL = tree.getroot()
print(rootWSDL.attrib['name'])

#-->Name of the file

推荐阅读