Elementtree find problem
Stefan Behnel
stefan_ml at behnel.de
Mon Apr 21 03:24:17 EDT 2008
Mike Slinn wrote:
> The following short Python program parses a KML file and displays the
> names of all Marks and Routes:
>
> from elementtree.ElementTree import ElementTree
> tree = ElementTree(file='test.kml')
> kml = tree.getroot()
> ns = 'http://earth.google.com/kml/2.1'
> for folder in kml.findall("{%s}Folder/{%s}Folder/{%s}name" % (ns, ns, ns)):
> print folder.text
>
> I want to modify the program to ignore Marks, and print out the
> coordinates of each Route. Seems ElementTree v1.3 will make this task
> much easier, but unfortunately the CheeseShop and the Gentoo Portage
> repostitory only have v1.2.7 at this time.
You can install the current developer version of ET 1.3 from here:
http://svn.effbot.org/public/elementtree-1.3
Or use lxml, which comes with full-fledged XPath support.
http://codespeak.net/lxml
> The following code is as
> close as I can get to what I want, but it doesn't run because I've
> attempted to use v1.3 syntax, ended up writing complete crap instead,
> and I can't understand the docs well enough for the v1.2.7 syntax.
> Perhaps someone can understand what I mean and give me a clue as to how
> to write this?
>
> from elementtree.ElementTree import ElementTree
>
> tree = ElementTree(file='test.kml')
> kml = tree.getroot()
> ns = 'http://earth.google.com/kml/2.1'
> for folders in kml.findall("{%s}Folder/{%s}Folder" % (ns, ns)):
> if folders["name"].text=='Routes':
> print folder.findall("{%s}LineString/{%s}coordinates" % (ns,
> ns))
What's "name" here? An attribute? Then this might work better:
if folders.get("name") == 'Routes':
or did you mean it to be a child node?
if folders.findtext("name") == 'Routes':
Stefan
More information about the Python-list
mailing list