【问题标题】:Retrieve attribute from XML node using namespace in Python在 Python 中使用命名空间从 XML 节点检索属性
【发布时间】:2020-03-18 10:55:07
【问题描述】:

我知道已经有一些从 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”的“name”属性 我尝试过以下操作:

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】:

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

    例如:

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

    【讨论】:

    • 谢谢。但是假设我有一个用例,其中有问题的节点不在根的正下方?我想找到一种方法,我可以明确指定我想要定位的节点,而不是它在结构中的位置。
    • 使用print(tree.find('wsdl:definitions', rootWSDL.nsmap).attrib['name']) 而不使用./
    • Adam:但是假设我有一个用例,其中有问题的节点不在根的正下方? 那么你为什么不首先问那个用例呢? ? @Rakesh 确实提供了一个合理的答案。您已经开始赏金,但问题中的 XML 没有更改。你到底在问什么?
    【解决方案2】:

    在您的示例中,您无法使用 find 找到 wsdl:definitions 节点,因为 rootWSDL 就是该节点。如果总是这样,只需使用 rootWSDL.attrib['name']。

    您当前的 xpath 将仅查找作为 rootWSDL 的直接子级的元素。如果您的意图是在文档中的任何位置查找其他命名空间节点,只需将其设为全局 xpath,即替换:

    './wsdl:targetElementName' 
    

    '//wsdl:targetElementName'
    

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多