Remove “xmlns:py…” with lxml.objectify

寵の児 提交于 2019-12-11 09:23:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!