简体   繁体   中英

Can't remove unecessary element from QName

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM