1 ==============================
2 The public C-API of lxml.etree
3 ==============================
5 As of version 1.1, lxml.etree provides a public C-API. This allows external
6 C extensions to efficiently access public functions and classes of lxml,
7 without going through the Python API.
9 The API is described in the file `etreepublic.pxd`_, which is directly
10 c-importable by extension modules implemented in Pyrex_ or Cython_.
12 .. _`etreepublic.pxd`: http://codespeak.net/svn/lxml/trunk/src/lxml/etreepublic.pxd
13 .. _Cython: http://www.cython.org
14 .. _Pyrex: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
18 1 Writing external modules in Cython
19 2 Writing external modules in C
22 Writing external modules in Cython
23 ----------------------------------
25 This is the easiest way of extending lxml at the C level. A Cython_
26 (or Pyrex_) module should start like this::
30 # import the public functions and classes of lxml.etree
31 cimport etreepublic as cetree
33 # import the lxml.etree module in Python
35 from lxml import etree
37 # initialize the access to the C-API of lxml.etree
38 cetree.import_lxml__etree()
40 From this line on, you can access all public functions of lxml.etree
41 from the ``cetree`` namespace like this::
43 # build a tag name from namespace and element name
44 py_tag = cetree.namespacedNameFromNsName("http://some/url", "myelement")
46 Public lxml classes are easily subclassed. For example, to implement
47 and set a new default element class, you can write Cython code like
50 from etreepublic cimport ElementBase
51 cdef class NewElementClass(ElementBase):
52 def set_value(self, myval):
53 self.set("my_attribute", myval)
55 etree.set_element_class_lookup(
56 etree.DefaultElementClassLookup(element=NewElementClass))
59 Writing external modules in C
60 -----------------------------
62 If you really feel like it, you can also interface with lxml.etree straight
63 from C code. All you have to do is include the header file for the public
64 API, import the ``lxml.etree`` module and then call the import function:
75 #include "libxml/xmlversion.h"
76 #include "libxml/encoding.h"
77 #include "libxml/hash.h"
78 #include "libxml/tree.h"
79 #include "libxml/xmlIO.h"
80 #include "libxml/xmlsave.h"
81 #include "libxml/globals.h"
82 #include "libxml/xmlstring.h"
84 /* lxml.etree specific includes */
85 #include "lxml-version.h"
86 #include "etree_defs.h"
92 Note that including ``etree.h`` does not automatically include the
93 header files it requires. Note also that the above list of common
94 includes may not be sufficient.