Can't remove unecessary element from QName

73 Views Asked by At

I'm trying to add namespaces in a xml that I'm generating so I tried this and came up with the code below:

from xml.etree import ElementTree as ET

NS1 = "http://www.w3.org/" 


ET.register_namespace("xsi", NS1) 

qname1 = ET.QName(NS1, "D")    # Element QName 

root = ET.Element("Database", {qname1:""},xmlns="http://www.staubli.com/") 

print(ET.tostring(root).decode())

This code gives me

<Database xmlns:xsi="http://www.w3.org/" xsi:D="" xmlns="http://www.staubli.com/" />

And i want

<Database xmlns:xsi="http://www.w3.org/" xmlns="http://www.staubli.com/">

So I want to get rid of the xsi:D="". But if I remove the "D" from my QName line, all the namespaces disappear.

Do you know how I can achieve this? Thank you.

1

There are 1 best solutions below

0
dabingsou On

I don't know what to do with etree. here's another solution.

from simplified_scrapy import SimplifiedDoc
xml = '''<Database />'''
doc = SimplifiedDoc(xml)
root = doc.Database
root.setAttrs({"xmlns:xsi":"http://www.w3.org/","xmlns":"http://www.staubli.com/"})
print (doc.html) # <Database xmlns:xsi="http://www.w3.org/" xmlns="http://www.staubli.com/" />
# Or
xml = '''<Database></Database>'''
doc = SimplifiedDoc(xml)
root = doc.Database
root.setAttrs({"xmlns:xsi":"http://www.w3.org/","xmlns":"http://www.staubli.com/"})
print (doc.html) # <Database xmlns:xsi="http://www.w3.org/" xmlns="http://www.staubli.com/"></Database>

Here are more examples: https://github.com/yiyedata/simplified-scrapy-demo/blob/master/doc_examples/edit_element.py