Home > Enterprise >  How to add namespace in existing xml file
How to add namespace in existing xml file

Time:09-28

Sample xml:

<abcd>

... Many contents here ...

</abcd>

I want to change sample file like below:

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

.... many contents here

</abcd>

So, my code is below, but when I printed out the document the result is same with the input file.

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())

How can I add the namespace and print out?

CodePudding user response:

in your code you're just creating a new abcd and don't do anything with it

try this

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())
  • Related