問題描述
我需要打開一個 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 中刪除命名空間和前綴的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!