似乎无法删除“ns0:”命名空间声明

7

我想做的事情就是读取一个本地的.xml文件(将其编码为UTF-8以便它具有正确的标题,并重新保存文件)。然而,当我运行以下代码时,它会在每个XML元素中添加可怕的“ns0:”声明:

import xml.etree.ElementTree as ET
import sys, os

# note that this is the *module*'s `register_namespace()` function
# WTF THIS SHOULD WORK....
ET.register_namespace("", "http://www.w3.org/2000/svg")

tree = ET.ElementTree() # instantiate an object of *class* `ElementTree`
tree.parse('//cbweb1/inetpub/x/sitemap/sitemap_index.xml')

tree.write('//cbweb1/inetpub/x/sitemap/test.xml', encoding = 'utf-8', xml_declaration=True)

我做错了什么??

顺便说一下,这是Python 2.7.x(已尝试使用3.4)

编辑:

输入:

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <sitemap>
    <loc>http://www.example.com/something.xml</loc>
    <lastmod>2014-05-01</lastmod>
  </sitemap>
</sitemapindex>

输出:

<?xml version="1.0" encoding="utf-8"?>
<ns0:sitemapindex xmlns:ns0="http://www.sitemaps.org/schemas/sitemap/0.9">
  <ns0:sitemap>
    <ns0:loc>http://www.example.com/something.xml</ns0:loc>
    <ns0:lastmod>2014-05-01</ns0:lastmod>
  </ns0:sitemap>
</ns0:sitemapindex>

输入是什么?输出是什么? - Joshua Taylor
@JoshuaTaylor,我对上面的原始帖子进行了编辑。 - Ray
1
如果默认命名空间应该是 http://www.sitemaps.org/schemas/sitemap/0.9,为什么要将其设置为 http://www.w3.org/2000/svg?难道不应该使用 ET.register_namespace("", "http://www.sitemaps.org/schemas/sitemap/0.9") 吗? - Joshua Taylor
哇,完全脑抽了!!那个可行!我这边真是惨败了。 - Ray
1
看着输出结果,我敢打赌我知道发生了什么。你遇到了类似的问题,然后从其他问题中复制/粘贴了解决方案,这给了你svg前缀,是吗?(最好的人都会犯这种错误。 :)) - Joshua Taylor
1个回答

8

如果原始输入中的默认命名空间为http://www.sitemaps.org/schemas/sitemap/0.9,如下所示:

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

然后,如果您使用设置将其设置为其他内容,则可以使用以下方式进行操作。
ET.register_namespace("", "http://www.w3.org/2000/svg")

在输出中,您需要声明其他命名空间http://www.sitemaps.org/schemas/sitemap/0.9。相反,您应该将其设置为相同的值:

ET.register_namespace("", "http://www.sitemaps.org/schemas/sitemap/0.9")

或者,您可以尝试根本不设置它; 也许输出中使用的命名空间与输入中存在的相同。


谢谢纠正,Joshua!接受了你的答案。 - Ray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接