XPath and XQuery in Python?

Nelson Minar nelson at monkey.org
Fri Jan 14 10:51:52 EST 2005


Nelson Minar <nelson at monkey.org> writes:
> Could someone help me get started using XPath or XQuery in Python?

I figured this out. Thanks for the help, John! Examples below.

I used this exercise as an opportunity to get something off my chest
about XML and Python - it's kind of a mess! More here:
  http://www.nelson.monkey.org/~nelson/weblog/tech/python/xpath.html

Here are my samples, in three libraries:

# PyXML

from xml.dom.ext.reader import Sax2
from xml import xpath
doc = Sax2.FromXmlFile('foo.opml').documentElement
for url in xpath.Evaluate('//@xmlUrl', doc):
  print url.value

# libxml2

import libxml2
doc = libxml2.parseFile('foo.opml')
for url in doc.xpathEval('//@xmlUrl'):
  print url.content

# ElementTree

from elementtree import ElementTree
tree = ElementTree.parse("foo.opml")
for outline in tree.findall("//outline"):
  print outline.get('xmlUrl')

Please see my blog entry for more commentary
  http://www.nelson.monkey.org/~nelson/weblog/tech/python/xpath.html



More information about the Python-list mailing list