如何从 Python3 中的类文件 xml 对象中查找节点?

How to find a node from a file-like xml object in Python3?

这些是类文件对象的内容toc:

<?xml version='1.0' encoding='utf-8'?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="eng">
    <head>
    ...
    </head>
    <docTitle>
        <text>THE_TEXT_I_WANT</text>
    </docTitle>

    ...
</ncx>

我现在的 Python3 代码:

import xml.etree.ElementTree as ET

# I get toc using open method in zipfile module
# toc : <zipfile.ZipExtFile name='toc.ncx' mode='r' compress_type=deflate>
toc_tree = ET.parse(toc)
for node in toc_tree.iter():
    print(node)
print(toc_tree.find('docTitle'))

for循环可以打印出所有节点但是find方法returnsNonefindall 方法 returns 也没什么。请任何人告诉我为什么?有没有更好的解决办法?

因为您的 XML 中有一个(默认)命名空间,搜索名为 docTitle 的元素将找不到任何结果,因为它正在搜索名为 docTitle 的未命名空间元素。相反,您需要使用带有完整命名空间 URI 的 clark 表示法:

toc_tree.find('{http://www.daisy.org/z3986/2005/ncx/}docTitle')