开发者

lxml and loops to create xml rss in python

I have been using lxml to create the xml of rss feed. But I am having trou开发者_开发技巧ble with the tags and cant really figure out how to to add a dynamic number of elements. Given that lxml seems to just have functions as parameters of functions, I cant seem to figure out how to loop for a dynamic number of items without remaking the entire page.

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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜