Setting values to an element using the objectify
API of the lxml
library, assigns the auto detected pytype
to that element and the required namespaces, by default.
For example, setting the root element:
root = objectify.Element('root')
print(etree.tostring(root, pretty_print=True).decode('utf-8'))
Outputs:
<root xmlns:py="http://codespeak.net/lxml/objectify/pytype"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" py:pytype="TREE"/>
or setting a value to a child element:
child = objectify.SubElement(root, 'child')
root.child = 'value'
print(etree.tostring(root, pretty_print=True).decode('utf-8'))
Outputs:
<root xmlns:py="http://codespeak.net/lxml/objectify/pytype"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" py:pytype="TREE">
<child py:pytype="str">value</child>
</root>
Even using the setattr of ObjectPath:
path = objectify.ObjectPath('root.vader.son')
path.setattr(root, 'Luke')
print(etree.tostring(root, pretty_print=True).decode('utf-8'))
Outputs:
<root xmlns:py="http://codespeak.net/lxml/objectify/pytype"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" py:pytype="TREE">
<child py:pytype="str">value</child>
<vader>
<son py:pytype="str">Luke</son>
</vader>
</root>
There are solutions that remove the pytype
and its namespaces after the element creation, using the deannotate()
function (ex. When using lxml, can the XML be rendered without namespace attributes?, Remove "xmlns:py..." with lxml.objectify). There are no solutions whatsoever that create the element without the pytype
and its namespaces from the beginning. Any ideas on how to do that?