我刚刚发现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>

最佳答案

如此处指出的:When using lxml, can the XML be rendered without namespace attributes?,这足以防止出现此xmlns标记:

objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)

09-10 06:43
查看更多