0

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.

Jack
  • 695
  • 10
  • 29

1 Answers1

1

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

dabingsou
  • 2,469
  • 1
  • 5
  • 8