如果我想用python创建一个简单的XML文件,我有什么选择?(库方面)
我想要的xml如下所示:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some vlaue2</field2>
</doc>
</root>
发布于 2011-04-04 23:36:48
lxml library包含一种非常方便的语法,称为E-factory。下面是我如何制作你给出的例子:
#!/usr/bin/python
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
print lxml.etree.tostring(the_doc, pretty_print=True)
输出:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
它还支持添加到已创建的节点,例如,在上面的操作之后,您可以这样说
the_doc.append(FIELD2('another value again', name='hithere'))
发布于 2015-05-02 21:27:26
Yattag或https://github.com/leforestier/yattag提供了一个有趣的http://www.yattag.org/来创建这样的文档(以及https://github.com/leforestier/yattag文档)。
它使用了context manager和with
关键字。
from yattag import Doc, indent
doc, tag, text = Doc().tagtext()
with tag('root'):
with tag('doc'):
with tag('field1', name='blah'):
text('some value1')
with tag('field2', name='asdfasd'):
text('some value2')
result = indent(
doc.getvalue(),
indentation = ' '*4,
newline = '\r\n'
)
print(result)
所以你会得到:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
发布于 2010-08-31 11:00:39
对于最简单的选择,我会选择minidom:http://docs.python.org/library/xml.dom.minidom.html。它内置于python标准库中,在简单的情况下可以直接使用。
下面是一个非常容易遵循的教程:http://www.boddie.org.uk/python/XML_intro.html
https://stackoverflow.com/questions/3605680
复制相似问题