【问题标题】:Can't seem to remove "ns0:" namespace declaration [duplicate]似乎无法删除“ns0:”命名空间声明 [重复]
【发布时间】:2014-05-01 22:07:31
【问题描述】:

我要做的只是读取一个本地 .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>

【问题讨论】:

  • 输入是什么?输出是什么?
  • @JoshuaTaylor,我对上面的原始帖子进行了编辑。
  • 如果默认命名空间应该是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") 吗?
  • 哇,全脑放屁!!这样可行!史诗般的失败是我的一部分。
  • 嘿,看看输出,我敢打赌我能看到发生了什么。你有一个类似的问题,然后复制/粘贴另一个问题的解决方案,它给了你 svg 前缀,是吗? (发生在我们最好的人身上。:))

标签: python xml


【解决方案1】:

如果原始输入中的默认命名空间为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 的更正!接受你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-14
  • 2019-03-22
  • 1970-01-01
  • 2023-01-24
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
相关资源
最近更新 更多