home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / share / doc / python-libxml2 / examples / tstxpath.py < prev    next >
Encoding:
Python Source  |  2004-02-23  |  1.4 KB  |  64 lines

  1. #!/usr/bin/python -u
  2. import sys
  3. import libxml2
  4.  
  5. #memory debug specific
  6. libxml2.debugMemory(1)
  7.  
  8. called = ""
  9.  
  10. def foo(ctx, x):
  11.     global called
  12.  
  13.     #
  14.     # test that access to the XPath evaluation contexts
  15.     #
  16.     pctxt = libxml2.xpathParserContext(_obj=ctx)
  17.     ctxt = pctxt.context()
  18.     called = ctxt.function()
  19.     return x + 1
  20.  
  21. def bar(ctxt, x):
  22.     return "%d" % (x + 2)
  23.  
  24. doc = libxml2.parseFile("tst.xml")
  25. ctxt = doc.xpathNewContext()
  26. res = ctxt.xpathEval("//*")
  27. if len(res) != 2:
  28.     print "xpath query: wrong node set size"
  29.     sys.exit(1)
  30. if res[0].name != "doc" or res[1].name != "foo":
  31.     print "xpath query: wrong node set value"
  32.     sys.exit(1)
  33. libxml2.registerXPathFunction(ctxt._o, "foo", None, foo)
  34. libxml2.registerXPathFunction(ctxt._o, "bar", None, bar)
  35. i = 10000
  36. while i > 0:
  37.     res = ctxt.xpathEval("foo(1)")
  38.     if res != 2:
  39.         print "xpath extension failure"
  40.         sys.exit(1)
  41.     i = i - 1
  42. i = 10000
  43. while i > 0:
  44.     res = ctxt.xpathEval("bar(1)")
  45.     if res != "3":
  46.         print "xpath extension failure got %s expecting '3'"
  47.         sys.exit(1)
  48.     i = i - 1
  49. doc.freeDoc()
  50. ctxt.xpathFreeContext()
  51.  
  52. if called != "foo":
  53.     print "xpath function: failed to access the context"
  54.     print "xpath function: %s" % (called)
  55.     sys.exit(1)
  56.  
  57. #memory debug specific
  58. libxml2.cleanupParser()
  59. if libxml2.debugMemory(1) == 0:
  60.     print "OK"
  61. else:
  62.     print "Memory leak %d bytes" % (libxml2.debugMemory(1))
  63.     libxml2.dumpMemory()
  64.