How to use XPath in Python?

Question :

How to use XPath in Python?,

Answer :

What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website?

,

 has a number of advantages:

  1. Compliance to the
  2. Active development and a community participation
  3. Speed. This is really a python wrapper around a C implementation.
  4. Ubiquity. The libxml2 library is pervasive and thus well tested.

Downsides include:

  1. Compliance to the . It’s strict. Things like default namespace handling are easier in other libraries.
  2. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.
  3. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.
Read More  How have Html entities inside asp.net page?

If you are doing simple path selection, stick with  ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.

Sample of libxml2 XPath Use


import libxml2    doc = libxml2.parseFile("tst.xml")  ctxt = doc.xpathNewContext()  res = ctxt.xpathEval("//*")  if len(res) != 2:      print "xpath query: wrong node set size"      sys.exit(1)  if res[0].name != "doc" or res[1].name != "foo":      print "xpath query: wrong node set value"      sys.exit(1)  doc.freeDoc()  ctxt.xpathFreeContext()  

Sample of ElementTree XPath Use

Read More  Is there some way of recycling a Crystal Reports dataset?

from elementtree.ElementTree import ElementTree  mydoc = ElementTree(file='tst.xml')  for e in mydoc.findall('/foo/bar'):      print e.get('title').text

That’s the answer How to use XPath in Python?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you

Read More  Generate sitemap on the fly