python / python/cpython

etree: Defining the default namespace prefix (`""`) with register_namespace has issues

未關閉
#118,416 4 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

extension-modules topic-XML type-bug
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Bug report

Bug description:

Granted the register_namespace() functionality should be used for 'well known namespace prefixes' but if the the default namespace prefix ("") is registered, the following issues can occur:

Duplicate default namespace attrs xmlns=''

import xml.etree.ElementTree as ET
ET.register_namespace("", "default")
e = ET.Element("{default}elem")
print(ET.tostring(e, default_namespace="otherdefault"))
# b'<elem xmlns="otherdefault" xmlns="default" />'

Incorrect serialisation (the noPrefixElem should raise an error but now it looks like it is in the default namespace):

import xml.etree.ElementTree as ET
ET.register_namespace("", "default")
e = ET.Element("{default}elem")
ET.SubElement(e, "noPrefixElem")
print(ET.tostring(e))
# b'<elem xmlns="default"><noPrefixElem /></elem>'

The two approaches to address this that I can think of are:

  • Raise an error if the default namespace is passed to register_namespace()
    • Lucky users that register "" but don't use the default prefix's URI anywhere or has every element qualified will have working code with no issues. This would cause their working code to break.
  • Handle it properly in ElementTree._namespaces() by setting the default_namespace var in that function from the global registry if the default_namespace argument is None
    • Existing code that 'works' may raise errors about ValueError: cannot use non-qualified names with default_namespace option, but at least erroneous xml would no longer be emitted
    • It may be possible to make it so code that was luckily unaffected still doesn't raise an error
    • May result in #61290

I'm happy to give the second option a try (with implementing any changes required for #61290) as I've also been looking into #57587 that also needs to handle potentially multiple definitions of the default_namespace. My current thinking is that if default_namespace is provided to _namespaces(), it takes precedence even if the default namespace is also defined in the global registry.

CPython versions tested on:

3.12, CPython main branch

Operating systems tested on:

macOS

Linked PRs
  • gh-118417

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

先從 xml.etree.ElementTree.register_namespace()、ElementTree._namespaces() 和 ET.tostring() 開始,然後重現 issue 中的兩個範例。在選擇預設命名空間的優先順序之前,檢視連結的 PR gh-118417 以及相關的命名空間行為。完成的標準是序列化不再輸出重複宣告,也不再默默地將未限定元素視為屬於預設命名空間。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
backend
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。