lxml和循环在python中创建xmlrss

lxml和循环在python中创建xmlrss,python,lxml,Python,Lxml,我一直在使用lxml创建rss提要的xml。但是我在标签方面遇到了麻烦,无法真正理解如何添加动态数量的元素。鉴于lxml似乎只是将函数作为函数的参数,我似乎无法理解如何在不重新创建整个页面的情况下循环动态数量的项 rss = page = ( E.rss( E.channel( E.title("Page Title"), E.link(""), E.description(""), E.item(

我一直在使用lxml创建rss提要的xml。但是我在标签方面遇到了麻烦,无法真正理解如何添加动态数量的元素。鉴于lxml似乎只是将函数作为函数的参数,我似乎无法理解如何在不重新创建整个页面的情况下循环动态数量的项

rss = page = (
      E.rss(
        E.channel(
          E.title("Page Title"),
   E.link(""),
   E.description(""),

            E.item(
                  E.title("Hello!!!!!!!!!!!!!!!!!!!!! "),
                  E.link("htt://"),
                  E.description("this is a"),
            ),
        )
      )
    )
说:


要创建子元素并将其添加到父元素,可以使用
append()
方法:

>>> root.append( etree.Element("child1") )
然而,这是如此普遍,以至于有一种更短、更有效的方法来实现这一点:子元素
工厂。它接受与
元素
工厂相同的参数,但还需要父元素作为第一个参数:

>>> child2 = etree.SubElement(root, "child2")
>>> child3 = etree.SubElement(root, "child3")


因此,您应该能够创建文档,然后说
channel=rss.find(“channel”)
,并使用上述任一方法向
channel
元素添加更多项。

Jason已经回答了您的问题;但是–仅供参考–您可以将任意数量的函数参数作为列表动态传递:
E.channel(*args)
,其中
args
将是
[E.title(
..
)、E.link(
..
)、
..
]
。类似地,关键字参数可以使用dict和双星(
**
)传递。看

channel = E.channel(E.title("Page Title"), E.link(""),E.description(""))
    for (title, link, description) in container:
        try:
                    mytitle = E.title(title)
                    mylink = E.link(link)
                    mydesc = E.description(description)
            item = E.item(mytitle, mylink, mydesc)
                except ValueError:
                    print repr(title)
                    print repr(link)
                    print repr(description)
                    raise
        channel.append(item)
    top = page = E.top(channel)