如何从Python xml etree ElementTree中的根元素中删除属性

How to remove attribute from root element in Python xml etree ElementTree

我的文件包含以下数据:

原版的:

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>

预期:

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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"},但是却得到了一个空字典。 有人可以帮忙吗?

赞赏!


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

删除,添加或修改名称空间可能非常困难。"普通"属性存储在元素的可写attrib属性中。 另一方面,名称空间映射无法通过API获得(在lxml库中,元素确实具有nsmap属性,但它是只读的)。

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

1
2
3
4
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字符串?


在标准库xml.etree.ElementTree中,没有删除属性的特殊方法,但是所有属性都存储在attrib中,该dictdict,并且可以从attrib中将任何属性作为<< x1>:

1
2
3
4
5
6
7
8
9
10
11
12
13
    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>'