如何在现有 xml 文件中添加命名空间

How to add namespace in existing xml file

样本xml:

<abcd>

... Many contents here ...

</abcd>

我想像下面这样更改示例文件:

<abcd xmlns="urn:myname" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                         xsi:schemaLocation="urn:myname myname.xsd">

.... many contents here

</abcd>

所以,我的代码如下,但是当我打印文档时,结果与输入文件相同。

attr_qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")
nsmap = {None: "urn:myname", 'xsi':"http://www.w3.org/2001/XMLSchema-instance"}
document = etree.parse(self.fname)
root = document.getroot()
root = etree.Element('abcd', {attr_qname: 'urn:myname myname.xsd'}, nsmap=nsmap)
print("Parsed : ", etree.tostring(document, pretty_print=True).decode())

如何添加命名空间并打印出来?

在您的代码中,您只是创建了一个新的 abcd 并且不对其进行任何操作

试试这个

attr_qname = etree.QName("http://www.w3.org/2001/XMLSchema-instance", "schemaLocation")
nsmap = {None: "urn:myname", 'xsi':"http://www.w3.org/2001/XMLSchema-instance"}
document = etree.parse(self.fname)
root = document.getroot()

abcd = root.find('abcd')
abcd.set('xmlns', "urn:myname")
abcd.set(attr_qname, "urn:myname myname.xsd")
print("Parsed : ", etree.tostring(root, pretty_print=True).decode())