我正在为旧系统使用旧版本的 Python (2.3),并且我没有可用的 ElementTree(从 2.5 开始......)。该xml.dom
包似乎是我用于解析和编辑 XML 文档的最佳接口,但如果您在这里发现一些不可行或明显错误的地方,请随时引导我转向另一个方向。
我无法更改已解析的 XML。我想将我的所有标签都设置为具有特定的前缀/命名空间,所以我编写了这个函数:
def recursive_set_ns(root):
# type: (Element) -> None
"""Set namespaces for all tags recursively by DFS."""
if (root.prefix is None) or (root.prefix == ""):
root.prefix = "some_prefix"
if not root.hasChildNodes():
# Probably not necessary, though good to have for logic.
return
for child_tag in root.childNodes:
recursive_set_ns(child_tag)
出于某种原因,该变量实际上确实得到了更新,但是当我使用orroot.prefix
将其打印出来时,此更改不会反映在 XML 文档中。document.toxml
document.writexml
为了给出一个实际的 MCVF,我认为这足以显示我遇到的问题:
from xml.dom import minidom
document_string = "<atag>Some text.</atag>"
document = minidom.parseString(document_string)
# documentElement is the "atag" object here.
document.documentElement.prefix = "pre"
# Expecting to see "<pre:atag>Some text.</pre:atag>"
print(document.toxml()) # instead prints the original document_string
你可以在这里演示。先感谢您!