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

我知道已经有一些从XML节点中检索特定属性的示例,但是我在使用名称空间的过程中并未取得成功。我可以检索没有任何名称空间的属性,例如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'对象没有属性'attrib'

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

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

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

例如:

from lxml import etree

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

#-->Name of the file
,

在您的示例中,找不到带有find的wsdl:definitions节点,因为rootWSDL是该节点。如果总是这样,请使用rootWSDL.attrib ['name']。

您当前的xpath将仅查找rootWSDL的直接子元素。如果您打算在文档中的任何位置找到其他命名空间节点,则只需使其成为全局xpath,即可替换:

'./wsdl:targetElementName' 

'//wsdl:targetElementName'
本文链接:https://www.f2er.com/3051407.html

大家都在问