lxml and loops to create xml rss in python

筅森魡賤 提交于 2019-12-02 03:24:38

Jason has answered your question; but – just FYI – you can pass any number of function arguments dynamically as a list: E.channel(*args), where args would be [E.title(...), E.link(...),...]. Similarly, keyword arguments can be passed using dict and two stars (**). See documentation.

This lxml tutorial says:


To create child elements and add them to a parent element, you can use the append() method:

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

However, this is so common that there is a shorter and much more efficient way to do this: the SubElement factory. It accepts the same arguments as the Element factory, but additionally requires the parent as first argument:

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

So you should be able to create the document, then say channel = rss.find("channel") and use either of the above methods to add more items to the channel element.

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!