0

我正在为旧系统使用旧版本的 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.toxmldocument.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

你可以在这里演示。先感谢您!

4

1 回答 1

0

我能够自己回答这个问题。

element.tagName = "pre:" + element.tagName

只编辑整个标签显然是有效的,所以我这样做了,而不是试图找到一个可以为我做的 API 调用。花了很多时间盯着文档来弄清楚这一点。我更改所有这些的代码现在看起来像:

def recursive_set_ns(root):
    # type: (Element) -> None
    """Set namespaces for all tags recursively by DFS."""
    if ":" not in root.tagName:  # leave existing namespaces alone
        root.tagName = "pre:" + root.tagName
    children = filter(lambda c: c.nodeType == c.ELEMENT_NODE, root.childNodes)
    for child_tag in children:
        recursive_set_ns(child_tag)
于 2018-06-19T15:22:42.970 回答