1

我的文件包含以下数据:

原来的:

<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <changefreq>daily</changefreq> <loc>http://www.example.com</loc></url></urlset>

预期的:

<?xml version="1.0" encoding="UTF-8"?><urlset> <url> <changefreq>daily</changefreq> <loc>http://www.example.com</loc></url></urlset>

我使用 etree 解析文件,我想从根元素 'urlset' 中删除属性

import xml.etree.ElementTree as ET

tree = ET.parse("/Users/hsyang/Downloads/VI-0-11-14-2016_20.xml")
root = tree.getroot()

print root.attrib
>> {}

root.attrib.pop("xmlns", None)

print root.attrib
>> {}
ET.tostring(root)

我以为我第一次打印 root.attrib 时应该得到 {xmlns:" http://www.sitemaps.org/schemas/sitemap/0.9 "} 但我得到了一个空字典。有人可以帮忙吗?

欣赏它!

4

2 回答 2

1

xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"看起来像一个常规属性,但它是一种特殊情况,即命名空间声明。

删除、添加或修改命名空间可能非常困难。“正常”属性存储在元素的可写attrib属性中。另一方面,命名空间映射并不容易通过 API 获得(在 lxml 库中,元素确实有一个nsmap属性,但它是只读的)。

我建议一个简单的文本搜索和替换操作,类似于使用 lxml 修改给定 xml 文档中的命名空间的答案。像这样的东西:

with open("input.xml", "r") as infile, open("output.xml", "w") as outfile:
    data = infile.read()
    data = data.replace(' xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"', '')
    outfile.write(data)

另请参阅如何使用 Python 将命名空间和前缀插入 XML 字符串?.

于 2016-12-05T16:32:57.613 回答
0

在标准库xml.etree.ElementTree中,没有删除属性的特殊方法,但所有属性都存储在 a attribwhich is a中dict,并且可以从 a 中删除任何属性attrib作为键dict

    import xml.etree.ElementTree as ET

    tree = ET.parse(file_path)
    root = tree.getroot()      

    print(root.attrib)  # {'xyz': '123'}

    root.attrib.pop("xyz", None)  # None is to not raise an exception if xyz does not exist

    print(root.attrib)  # {}

    ET.tostring(root)
    '<urlset> <url> <changefreq>daily</changefreq> <loc>http://www.example.com</loc></url></urlset>'
于 2016-12-02T06:07:34.283 回答