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

问题描述 投票:0回答:1

[我知道已经有一些从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

python python-3.x xml wsdl
1个回答
0
投票

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

Ex:

from lxml import etree

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

#-->Name of the file
© www.soinside.com 2019 - 2024. All rights reserved.