python - Python 2 xml.dom - 更改元素前缀
问题描述
我正在为旧系统使用旧版本的 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
你可以在这里演示。先感谢您!
解决方案
我能够自己回答这个问题。
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)
推荐阅读
- php - 如何过滤PHP中键的值?
- php - Why is this e-mail form using validation resulting in an error?
- applescript - 在 web 表单中输入值并使用 applescript 按下返回键
- angular - Angular:ngModel 错误,因为我使用的是数组
- c++ - 调用接受 unique_ptr 对象的函数
- python - Selenium 不获取 url(3 行 python)
- html - Laravel 表单动作为空
- amazon-web-services - 查看 Amazon S3 上当前的请求数和数据传输数
- php - 在搜索功能中使用 PHP str_replace 不会返回所需的结果
- android - 无法从 Android 10 上的 BroadcastReceiver 开始活动