Remove namespace and prefix from xml in python using lxml(使用 lxml 从 python 中的 xml 中删除命名空间和前缀)
问题描述
我需要打开一个 xml 文件并对其进行一些更改,其中一项更改是删除名称空间和前缀,然后保存到另一个文件.这是xml:
I have an xml file I need to open and make some changes to, one of those changes is to remove the namespace and prefix and then save to another file. Here is the xml:
<?xml version='1.0' encoding='UTF-8'?>
<package xmlns="http://apple.com/itunes/importer">
<provider>some data</provider>
<language>en-GB</language>
</package>
我可以进行我需要的其他更改,但不知道如何删除命名空间和前缀.这是我需要的 reusklt xml:
I can make the other changes I need, but can't find out how to remove the namespace and prefix. This is the reusklt xml I need:
<?xml version='1.0' encoding='UTF-8'?>
<package>
<provider>some data</provider>
<language>en-GB</language>
</package>
这是我的脚本,它将打开并解析 xml 并保存它:
And here is my script which will open and parse the xml and save it:
metadata = '/Users/user1/Desktop/Python/metadata.xml'
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
open(metadata)
tree = etree.parse(metadata, parser)
root = tree.getroot()
tree.write('/Users/user1/Desktop/Python/done.xml', pretty_print = True, xml_declaration = True, encoding = 'UTF-8')
那么我将如何在脚本中添加代码来删除命名空间和前缀?
So how would I add code in my script which will remove the namespace and prefix?
推荐答案
按照 Uku Loskit 的建议替换标签.除此之外,使用 lxml.objectify.deannotate.
Replace tag as Uku Loskit suggests. In addition to that, use lxml.objectify.deannotate.
from lxml import etree, objectify
metadata = '/Users/user1/Desktop/Python/metadata.xml'
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(metadata, parser)
root = tree.getroot()
####
for elem in root.getiterator():
if not hasattr(elem.tag, 'find'): continue # (1)
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i+1:]
objectify.deannotate(root, cleanup_namespaces=True)
####
tree.write('/Users/user1/Desktop/Python/done.xml',
pretty_print=True, xml_declaration=True, encoding='UTF-8')
更新
Comment
等一些标签在访问 tag
属性时会返回一个函数.为此增加了一名警卫.(1)
Some tags like Comment
return a function when accessing tag
attribute. added a guard for that. (1)
这篇关于使用 lxml 从 python 中的 xml 中删除命名空间和前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 lxml 从 python 中的 xml 中删除命名空间和前缀


基础教程推荐
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01