473,387 Members | 1,890 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

XPath and XQuery in Python?

Could someone help me get started using XPath or XQuery in Python? I'm
overwhelmed by all the various options and am lacking guidance on what
the simplest way to go is. What library do I need to enable three line
Python programs to extract data with XPath expressions?

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.
http://www.xml.com/pub/a/2004/10/13/py-xml.html
Jul 18 '05 #1
3 6903
On Wed, Jan 12, 2005 at 12:09:58AM +0000, Nelson Minar wrote:
Could someone help me get started using XPath or XQuery in Python? I'm
overwhelmed by all the various options and am lacking guidance on what
the simplest way to go is. What library do I need to enable three line
Python programs to extract data with XPath expressions?

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:

#!/usr/bin/env python
import libxml2
import sys

def grep(what, where):
doc = libxml2.parseDoc(where)
for found in doc.xpathEval(what):
found.saveTo(sys.stdout, format=True)

if __name__ == '__main__':
try:
what = sys.argv[1]
except IndexError:
sys.exit("Usage: %s pattern file ..." % sys.argv[0])
else:
for where in sys.argv[2:]:
grep(what, file(where).read())

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

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFB5waUgPqu395ykGsRAm/IAKCbwTqV86ZypBFbF9xBG2c3PVqzRQCfYTUb
+4+hVntBxGn86Qbzb6FsPPM=
=0gY7
-----END PGP SIGNATURE-----

Jul 18 '05 #2
Nelson Minar <ne****@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...hon/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...hon/xpath.html
Jul 18 '05 #3
Interesting discussion. My own thoughts:

http://www.oreillynet.com/pub/wlg/6224
http://www.oreillynet.com/pub/wlg/6225

Meanwhile, please don't make the mistake of bothering with XQuery.
It's despicable crap. And a huge impedance mismatch with Python.
--Uche

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: inquirydog | last post by:
Can anyone explain to me why the following XQuery expression (a simple xpath expression) returns a different result than the same expression in xslt? document("document.xml")//a/@b For the...
1
by: Jeff Kish | last post by:
Hi. Can someone tell me when xslt, xpath, xquery are appropriate technologies to consider? I really know nothing about xslt except it is about transforming xml, (but I'm about to embark on a...
8
by: Terry P | last post by:
Are there any tools (java classes, tag libraries) which can translate xpath statements into a SQL query? Given an xpath query which has a predicate that filters node values or attributes, I want...
1
by: Philipp Schumann | last post by:
Hi .NET XML fans, does anyone know ad hoc whether support for the above standards is planned for .NET 2.0? I suppose this would be extremely valuable for many folks... Thanks, Phil
6
by: Chua Wen Ching | last post by:
Hi there, I had this xml file with me (not yet consider implementing xml namespaces yet). <?xml version='1.0'?> <Object> <Windows> <EID>1</EID> <EDesc>Error 1</EDesc> </Windows>
1
by: Sergey Dubinets | last post by:
In effort to prioritize our goals we composed the list of random features each of them may add value to set of XSLT tools offered from Microsoft. 1. XSLTc (Compiler for XSLT...
3
by: Bloody Viking | last post by:
Namaste, Y'all! I've got a valid XQuery expression that I need to convert to XPath 2.0. This expression will be stored in a resource file and applied to XML by a Java program with saxon8.jar...
2
by: henryrhenryr | last post by:
Hi I know the title's a bit odd. I'm trying to set up an XQuery for which the xpath is set previously according to input parameters. If I was going to do this normally I'd do something like: ...
4
by: ducttape | last post by:
Hi, I have been trying for several days to read XML files into my program. I have been following several good tutorials on the internet, but I am struggling because the particular XML files that I...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.