我有一个对象,它是列表类型的。print type(result)返回<type 'list'>。有没有自动转换成XML的函数?
发布于 2014-04-15 22:03:29
使用yattag库:
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('persons'):
for person in persons_dict:
doc.stag('person', **person):
result = doc.getvalue()发布于 2014-04-15 21:59:00
有一个非常简单的dict2xml库可以很容易地做到这一点,即使是像嵌套列表这样的复杂结构也可以得到很好的支持:
示例:
from dict2xml import dict2xml as xmlify
data = [
{"a": 1},
{"a": 2},
{"a": 3},
{"a": [
{"b": 1},
{"b": 2},
{"b": 3},
]}
]
print xmlify(data, wrap="all", indent=" ")结果:
<all>
<a>1</a>
</all>
<all>
<a>2</a>
</all>
<all>
<a>3</a>
</all>
<all>
<a>
<b>1</b>
</a>
<a>
<b>2</b>
</a>
<a>
<b>3</b>
</a>
</all>发布于 2014-04-15 21:31:40
从lxml检查objectify和E-factory。
E = objectify.E
result = [{ 'a': 1 }, {'a': 2} , {'a': 3}]
child_tags = [E.mytag(el) for el in result]
xml = E.root(*child_tags)
etree.tostring(xml, pretty_print=True)E为任何标签提供了构造函数。在我的示例中,列表中的每个元素都有标记mytag,每个标记都有对应于dict键的属性。因此,生成的xml将是:
<root xmlns:py="http://codespeak.net/lxml/objectify/pytype"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<mytag a="1"/>
<mytag a="2"/>
<mytag a="3"/>
</root>https://stackoverflow.com/questions/23085118
复制相似问题