ElementTree.find doesn't use registered namespaces when .find is called, and the inconsistency between ElementTree and ElementPath in how namespaces are defined
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
example xml: xml/example.xml
<root>
<h:title xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:title>
<f:table xmlns:f="http://www.w3.org/TR/html4/">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
minimal example
import xml.etree.ElementTree as ET
ns = {"h": "http://www.w3.org/TR/html4/", "f": "http://www.w3.org/TR/html4/"}
for prefix, uri in ns.items():
ET.register_namespace(prefix, uri)
tree = ET.parse("xml/example.xml")
print(tree._root) # <Element 'root' at 0x000002F6570FD940>
print(tree.find(".//{http://www.w3.org/TR/html4/}title")) # <Element '{http://www.w3.org/TR/html4/}title' at 0x000002F6570FD9E0>
print(tree.find(".//h:title", namespaces=ns)) # <Element '{http://www.w3.org/TR/html4/}title' at 0x000002F6570FD9E0>
print(tree.find(".//f:table", namespaces=ns)) # <Element '{http://www.w3.org/TR/html4/}table' at 0x000002F6570FDC60>
print(tree.find(".//f:table")) # SyntaxError: prefix 'f' not found in prefix map
When using the ET.register_namespace function the docstring mentions that it is global. But then when .find is used on a ElementTree instance the namespaces isn't passed on to the ElementPath that is used to find the element.
during the dig as to why the global register wasn't registering i also found an inconsistency in the way the namespaces are define between the ElementTree and the ElementPath:
https://github.com/python/cpython/blob/3490a99046078e4f9df7ac7570f62a0181bb3b89/Lib/xml/etree/ElementTree.py#L996
At the end of the register_namespace function:
_namespace_map[uri] = prefix
https://github.com/python/cpython/blob/3490a99046078e4f9df7ac7570f62a0181bb3b89/Lib/xml/etree/ElementPath.py#L85C46-L85C64
At the end of the xpath_tokenizer function:
namespaces[prefix]
the ElementTree also doesn't allow for multiple prefixes to point to the same URI where the ElementPath class has no issue with it, which i assume is a choice to allow for the serlization of the xml?
Linked PRs
- gh-140364
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
先閱讀 Lib/xml/etree/ElementTree.py 中的命名空間處理,尤其是 register_namespace,並將其與 Lib/xml/etree/ElementPath.py 中的 xpath_tokenizer 進行比較。檢視連結的 PR gh-140364 和提供的 XML 範例;當命名空間行為和前綴處理與已達成共識的解決方案一致時,即表示完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- backend
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 30/100