gpt4 book ai didi

python - 如何在 python 中编写带有命名空间的 XML 元素

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:08 24 4
gpt4 key购买 nike

我刚刚尝试使用这个 python 2.5 代码片段来编写一些 XML:

xmldoc = xml.dom.minidom.Document()
feed = xmldoc.createElementNS("http://www.w3.org/2005/Atom", "feed")
xmldoc.appendChild(feed)
print xmldoc.toprettyxml()

我期望输出如下所示:

<?xml version="1.0" ?>
<feed xmlns="http://www.w3.org/2005/Atom" />

相反,我得到了这个:

<?xml version="1.0" ?>
<feed />

显然 XML 命名空间在这里被默默地忽略了。我做错了什么?

最佳答案

minidom does not support命名空间规范化。我知道的唯一解决方法是明确设置 xmlns 属性

xmldoc.documentElement.setAttribute('xmlns', 'http://www.w3.org/2005/Atom')

关于python - 如何在 python 中编写带有命名空间的 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2306149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com