Skip to main content
 首页 » 编程设计

python之在 Python 中使用命名空间从 XML 节点检索属性

2025年05月04日17jpfss

我知道已经有一些从 XML 节点检索特定属性的示例,但我在使用命名空间时还没有成功。我能够检索没有任何 namespace 的属性,例如 this example .

假设我有以下“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' object has no attribute 'attrib'

不管怎样,我使用的 Python 版本是 3.7.5

请您参考如下方法:

您可以直接从根访问它。

例如:

from lxml import etree 
 
tree = etree.parse("example.wsdl") 
rootWSDL = tree.getroot() 
print(rootWSDL.attrib['name']) 
 
#-->Name of the file