I have this problem a lot with Python and XML. Even with Uche's
excellent yearly roundups I have a hard time finding how to do fancy
things with XML in Python. I think it's a bit like web server
frameworks in Python - too many choices.
my own favorite is libxml2. Something like the following:
def grep(what, where):
doc = libxml2.parseDoc(where)
for found in doc.xpathEval(what):
if __name__ == '__main__':
what = sys.argv
sys.exit("Usage: %s pattern file ..." % sys.argv)
for where in sys.argv[2:]:
although you might want to be smarter with the errors...
John Lenton (jo...@grulic.org.ar) -- Random fortune:
The whole world is a scab. The point is to pick it constructively.
-- Peter Beard
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:
Here are my samples, in three libraries:
from xml.dom.ext.reader import Sax2
from xml import xpath
doc = Sax2.FromXmlFile('foo.opml').documentElement
for url in xpath.Evaluate('//@xmlUrl', doc):
doc = libxml2.parseFile('foo.opml')
for url in doc.xpathEval('//@xmlUrl'):
from elementtree import ElementTree
tree = ElementTree.parse("foo.opml")
for outline in tree.findall("//outline"):
Please see my blog entry for more commentary
Meanwhile, please don't make the mistake of bothering with XQuery.
It's despicable crap. And a huge impedance mismatch with Python.