Links

Lists

Latest Updates

Ruby On Rails List
Python list
Advanced Java
The JavaScript List
Apache Users
Full Disclosure
Linux Security

Search the archives!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Simple elementtree question


  • From: stefan.behnel-n05pAM at web.de (Stefan Behnel)
  • Subject: Simple elementtree question
  • Date: Fri, 31 Aug 2007 10:31:23 +0200

IamIan wrote:
> Thank you very much! That did it.
> 
> In the source XML <item> tags have rdf:about attributes with the link
> to the story, and it was here I planned on grabbing the link and
> matching it up with the <title> child text. After seeing the output of
> elmenttree's getiterator() though, it now looks like each item, title,
> description, and link is a separate element...
> 
> I could use a dictionary or lists to match the first title to the
> first link, but is there a more elegant way in elementtree (or
> otherwise) to do this?

You can iterate over the channel Elements and then select the title child
(el.find()) to see if it's interesting.

You can also try lxml.etree, which supports XPath:

   >>> from lxml import etree
   >>> find_channel = etree.XPath("//channel[title = $title]")

   >>> tree = etree.parse("http://somewhere/the_document.xml";)
   >>> channel = find_channel(tree, title="example title")

   >>> print channel.findtext("link")

or lxml.objectify:

   >>> from lxml import etree, objectify
   >>> find_channel = etree.XPath("//channel[title = $title]")

   >>> tree = objectify.parse("http://somewhere/the_document.xml";)
   >>> channel = find_channel(tree, title="example title")

   >>> print channel.title, channel.link

http://codespeak.net/lxml

Stefan