python - 在 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
解决方案
您可以直接从根目录访问它。
前任:
from lxml import etree
tree = etree.parse("example.wsdl")
rootWSDL = tree.getroot()
print(rootWSDL.attrib['name'])
#-->Name of the file
推荐阅读
- chef-infra - 刀命令的ChefDk问题
- soap - WSO2 身份服务器密码更改,出现问题“无法访问用户的目录服务”
- php - ajax 请求未加载,因为服务器端 php 文件不可用
- html - HTML 不自动完成或提供选项
- swiftui - SwiftUI – 如何使用列表项点击更改 @State 属性?
- r - 基于条件的列总和
- javascript - 需要将随机生成的数字按数字顺序排序
- android - 如何在 Kotlin 中自定义 Android Studio 的导入顺序以忽略它们是否是“静态”导入?
- sql - 我需要将此查询限制为 1000 条记录并在 TOTAL 字段中显示 count(),我该怎么做?
- perl - 使用 Math::Polygon 确定点是否在多边形内。不工作