您应该更仔细地阅读文档,特别是有关使用命名空间解析 XML,其中包含一个几乎正是您想要的示例。
但即使没有文档,答案实际上也包含在您的示例输出中。当您打印文档的根元素时...
>>> tree = etree.parse(open('data.xml'))
>>> root = tree.getroot()
>>> root
<Element {http://www.docusign.net/API/3.0}DocuSignEnvelopeInformation at 0x7f972cd079e0>
...你可以看到它打印了根元素名称(DocuSignEnvelopeInformation
)带有命名空间前缀({http://www.docusign.net/API/3.0}
)。您可以使用相同的前缀作为参数的一部分findall
:
>>> root.findall('{http://www.docusign.net/API/3.0}Email')
但这本身是行不通的,因为这只会发现Email
根元素的直接子元素。您需要提供一个元素路径表达引起findall
执行整个文档的搜索。这有效:
>>> root.findall('.//{http://www.docusign.net/API/3.0}Email')
[<Element {http://www.docusign.net/API/3.0}Email at 0x7f972949a6c8>]
您还可以使用 XPath 和名称空间前缀执行类似的搜索,如下所示:
>>> root.xpath('//docusign:Email',
... namespaces={'docusign': 'http://www.docusign.net/API/3.0'})
[<Element {http://www.docusign.net/API/3.0}Email at 0x7f972949a6c8>]
这使您可以使用类似 XML 的namespace:
前缀而不是 LXML 命名空间语法。