我刚刚发现了lxml.objectify
,这对于读/写简单的XML文件来说似乎很容易。
首先,使用lxml.objectify
是个好主意吗?例如,它是否已经成熟并且仍在发展中并且可能在将来可用?
其次,如何阻止objectify
在下面的输出中添加xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str"
等标记?
输入:config.xml
<?xml version="1.0" encoding="utf-8"?>
<Test>
<MyElement1>sdfsdfdsfd</MyElement1>
</Test>
代码
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)
输出
<Test>
<MyElement1>sdfsdfdsfd</MyElement1>
<Information xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str">maybe</Information>
</Test>
答案 0 :(得分:2)
正如此处指出的那样:When using lxml, can the XML be rendered without namespace attributes?,这足以阻止此xmlns
标记出现:
objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)