我想迭代一个列表,并为每个列表元素在我的XML中创建一个子条目。要创建XML,我将lxml与etree一起使用。我可以做:
heads = ["foo", "foobar", "fooboo"]
child1 = etree.SubElement(root, heads[0])
child2 = etree.SubElement(root, heads[1])
...但是我想要自动完成它--如果有10个列表项,应该在XML中有10个子条目。我试过这样的方法:
for i_c, i in enumerate(heads):
a = "child_%i = etree.SubElement(root, %s)" % (i_c, i)
exec a我对Python很陌生..。所以请不要介意。:)
你好,简
发布于 2014-12-25 18:41:35
你可以用:
import lxml.etree as etree
root = etree.Element('root')
heads = ["foo", "foobar", "fooboo"]
for head in heads:
etree.SubElement(root, head)您不需要定义child_n,因为您可以通过root[n]访问它们
In [114]: list(root)
Out[114]:
[<Element foo at 0x7fa434bdf680>,
<Element foobar at 0x7fa434bdf560>,
<Element fooboo at 0x7fa434bdfab8>]
In [115]: root[1]
Out[115]: <Element foobar at 0x7fa434bdf560>提示:每当您开始用数字命名变量(例如child_1、child_2)时,很有可能使用一个变量(例如root),它是元组、列表或dict (在本例中是支持类列表索引的Element )。
因此,如果root不类似列表,并且希望收集列表中的子元素,则可以使用
child = list()
for head in heads:
child.append(etree.SubElement(root, head))然后,而不是child_n,您可以使用child[n-1]访问nth子级(因为child[n-1]使用基于0的索引)。
https://stackoverflow.com/questions/27649767
复制相似问题