首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从列表中创建XML子程序

从列表中创建XML子程序
EN

Stack Overflow用户
提问于 2014-12-25 18:36:55
回答 1查看 35关注 0票数 0

我想迭代一个列表,并为每个列表元素在我的XML中创建一个子条目。要创建XML,我将lxml与etree一起使用。我可以做:

代码语言:javascript
复制
heads = ["foo", "foobar", "fooboo"]

child1 = etree.SubElement(root, heads[0])
child2 = etree.SubElement(root, heads[1])
...

但是我想要自动完成它--如果有10个列表项,应该在XML中有10个子条目。我试过这样的方法:

代码语言:javascript
复制
for i_c, i in enumerate(heads):
     a = "child_%i = etree.SubElement(root, %s)" % (i_c, i)
     exec a

我对Python很陌生..。所以请不要介意。:)

你好,简

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-25 18:41:35

你可以用:

代码语言:javascript
复制
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]访问它们

代码语言:javascript
复制
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_1child_2)时,很有可能使用一个变量(例如root),它是元组、列表或dict (在本例中是支持类列表索引的Element )。

因此,如果root不类似列表,并且希望收集列表中的子元素,则可以使用

代码语言:javascript
复制
child = list()
for head in heads:
    child.append(etree.SubElement(root, head))

然后,而不是child_n,您可以使用child[n-1]访问nth子级(因为child[n-1]使用基于0的索引)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27649767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档