2010-01-20 29 views
2

我一直在使用lxml创建rss提要的xml。但是我遇到了标签问题,无法真正弄清楚如何添加动态数量的元素。考虑到lxml似乎只有函数作为函数的参数,我似乎无法弄清楚如何循环动态数量的项目,而无需重新制作整个页面。lxml和循环在python中创建xml rss

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"), 
      ), 
     ) 
    ) 
    ) 

回答

2
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) 
4

This lxml tutorial说:


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

>>> root.append(etree.Element("child1")) 

然而,这是很常见的,有一个更短,更有效的方法来做到这一点:SubElement工厂。它接受相同的参数Element工厂,但还需要家长作为第一个参数:

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

所以,你应该能够创建文档,然后说channel = rss.find("channel"),并使用上述任何一种方法,添加更多项目到channel元素。

5

Jason已回答你的问题;但 - 只是供参考 - 您可以动态地将任意数量的函数参数作为列表传递:E.channel(*args),其中args将是[E.title( ... ), E.link( ... ), ... ]。同样,关键字参数可以使用字典和两颗星(**)传递。请参阅documentation