问题
I just discovered lxml.objectify
which seems nice and easy for reading/writing simple XML files.
Firstly, is it a good idea to use lxml.objectify
? For instance is it mature and still developed and likely to be available in the future?
Secondly, how do I prevent objectify
from addding markup like xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str"
in the output below ?.
Input : config.xml
<?xml version="1.0" encoding="utf-8"?>
<Test>
<MyElement1>sdfsdfdsfd</MyElement1>
</Test>
Code
from lxml import etree, objectify
with open('config.xml') as f:
xml = f.read()
root = objectify.fromstring(xml)
root.Information = 'maybe'
print etree.tostring(root, pretty_print=True)
Output
<Test>
<MyElement1>sdfsdfdsfd</MyElement1>
<Information xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str">maybe</Information>
</Test>
回答1:
As pointed out here : When using lxml, can the XML be rendered without namespace attributes?, this is enough to prevent this xmlns
markup to appear :
objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)
来源:https://stackoverflow.com/questions/21767300/remove-xmlnspy-with-lxml-objectify