473,779 Members | 2,089 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6935
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.parseDo c(where)
for found in doc.xpathEval(w hat):
found.saveTo(sy s.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).rea d())

although you might want to be smarter with the errors...

--
John Lenton (jo**@grulic.or g.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)

iD8DBQFB5waUgPq u395ykGsRAm/IAKCbwTqV86ZypB FbF9xBG2c3PVqzR QCfYTUb
+4+hVntBxGn86Qb zb6FsPPM=
=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.rea der import Sax2
from xml import xpath
doc = Sax2.FromXmlFil e('foo.opml').d ocumentElement
for url in xpath.Evaluate( '//@xmlUrl', doc):
print url.value

# libxml2

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

# ElementTree

from elementtree import ElementTree
tree = ElementTree.par se("foo.opml")
for outline in tree.findall("//outline"):
print outline.get('xm lUrl')

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
2046
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 following sample document: <root> <a b="1" />
1
1412
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 learning campaign). As you may have noticed from other postings, I know a very small amount about XQuery (and thus XPath).
8
7583
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 help constructing the Where clause of a SQL statement that will mirror the expressions and functions contained in the predicate. Such a tool may require an XML to DB mapping or it would need to make assumptions about the structure of the...
1
1750
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
15511
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
2420
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 stylesheets, that generates .NET assemblies) 2. Performance improvements in the XslCompiledTransform
3
3566
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 (I'm pretty sure it's v.8.7). The manifest from the jar file follows: Manifest-Version: 1.0 Ant-Version: Apache Ant 1.7.0 Created-By: 1.5.0_06-b05 (Sun Microsystems Inc.) Project-Name: Saxon-B
2
1739
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: let $first := data($node//h2)
4
9044
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 am reading have several nested fields: <?xml version="1.0" encoding="UTF-8" ?> <xml> <records> <record> <database name="test.enl">test</database> <contributors> <authors> <author>
0
9636
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10306
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10139
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
6727
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.