[英]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
方法返回None
。 findall
方法也不返回任何內容。 請有人告訴我為什么? 有更好的解決方案嗎?
因為您的XML中有一個(默認)名稱空間,所以搜索名為docTitle
元素將找不到任何內容,因為它正在搜索名為docTitle
未命名空間的元素。 相反,您需要對完整的名稱空間URI使用clark表示法:
toc_tree.find('{http://www.daisy.org/z3986/2005/ncx/}docTitle')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.