Bas*_*asj 2 python xml lxml xml-parsing
我刚刚发现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>
Run Code Online (Sandbox Code Playgroud)
代码
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)
Run Code Online (Sandbox Code Playgroud)
输出
<Test>
<MyElement1>sdfsdfdsfd</MyElement1>
<Information xmlns:py="http://codespeak.net/lxml/objectify/pytype" py:pytype="str">maybe</Information>
</Test>
Run Code Online (Sandbox Code Playgroud)
正如这里所指出的:当使用lxml时,可以在没有命名空间属性的情况下呈现XML吗?,这足以防止xmlns出现此标记:
objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1498 次 |
| 最近记录: |