使用 lxml.objectify 删除“xmlns:py...”

2024-01-07

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

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>

正如这里指出的:使用lxml时,可以在没有命名空间属性的情况下呈现XML吗? https://stackoverflow.com/questions/5084730/when-using-lxml-can-the-xml-be-rendered-without-namespace-attributes,这足以防止这种情况xmlns要出现的标记:

objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 lxml.objectify 删除“xmlns:py...” 的相关文章

随机推荐