Blame doc/python.html

Packit 423ecb
Packit 423ecb
Packit 423ecb
<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><link rel="SHORTCUT ICON" href="/favicon.ico" /><style type="text/css">
Packit 423ecb
TD {font-family: Verdana,Arial,Helvetica}
Packit 423ecb
BODY {font-family: Verdana,Arial,Helvetica; margin-top: 2em; margin-left: 0em; margin-right: 0em}
Packit 423ecb
H1 {font-family: Verdana,Arial,Helvetica}
Packit 423ecb
H2 {font-family: Verdana,Arial,Helvetica}
Packit 423ecb
H3 {font-family: Verdana,Arial,Helvetica}
Packit 423ecb
A:link, A:visited, A:active { text-decoration: underline }
Packit 423ecb
</style><title>Python and bindings</title></head><body bgcolor="#8b7765" text="#000000" link="#a06060" vlink="#000000">
Action against software patentsGnome2 LogoW3C LogoRed Hat Logo
Made with Libxml2 Logo

The XML C parser and toolkit of Gnome

Python and bindings

<center>Developer Menu</center>
<form action="search.php" enctype="application/x-www-form-urlencoded" method="get"><input name="query" type="text" size="20" value="" /><input name="submit" type="submit" value="Search ..." /></form>
<center>API Indexes</center>
<center>Related links</center>

There are a number of language bindings and wrappers available for

Packit 423ecb
libxml2, the list below is not exhaustive. Please contact the xml-bindings@gnome.org
Packit 423ecb
(archives) in
Packit 423ecb
order to get updates to this list or to discuss the specific topic of libxml2
Packit 423ecb
or libxslt wrappers or bindings:

    Packit 423ecb
      
  • Libxml++ seems the
  • Packit 423ecb
        most up-to-date C++ bindings for libxml2, check the documentation
    Packit 423ecb
        and the examples.
    Packit 423ecb
      
  • There is another C++ wrapper
  • Packit 423ecb
        based on the gdome2 bindings maintained by Tobias Peters.
    Packit 423ecb
      
  • and a third C++ wrapper by Peter Jones <pjones@pmade.org>
  • Packit 423ecb
        

    Website: http://pmade.org/pjones/software/xmlwrapp/

    Packit 423ecb
      
    Packit 423ecb
      
  • XML::LibXML Perl
  • Packit 423ecb
          bindings are available on CPAN, as well as XML::LibXSLT
    Packit 423ecb
          Perl libxslt
    Packit 423ecb
          bindings.
    Packit 423ecb
      
  • If you're interested into scripting XML processing, have a look at XSH an XML editing shell based on
  • Packit 423ecb
        Libxml2 Perl bindings.
    Packit 423ecb
      
  • Dave Kuhlman provides an
  • Packit 423ecb
        earlier version of the libxml/libxslt wrappers for Python.
    Packit 423ecb
      
  • Gopal.V and Peter Minten develop libxml#, a set of
  • Packit 423ecb
        C# libxml2 bindings.
    Packit 423ecb
      
  • Petr Kozelka provides Pascal units to glue
  • Packit 423ecb
        libxml2 with Kylix, Delphi and other Pascal compilers.
    Packit 423ecb
      
  • Uwe Fechner also provides idom2, a DOM2
  • Packit 423ecb
        implementation for Kylix2/D5/D6 from Borland.
    Packit 423ecb
      
  • There is bindings for Ruby
  • Packit 423ecb
        and libxml2 bindings are also available in Ruby through the libgdome-ruby module
    Packit 423ecb
        maintained by Tobias Peters.
    Packit 423ecb
      
  • Steve Ball and contributors maintains libxml2 and libxslt bindings for
  • Packit 423ecb
        Tcl.
    Packit 423ecb
      
  • libxml2 and libxslt are the default XML libraries for PHP5.
  • Packit 423ecb
      
  • LibxmlJ is
  • Packit 423ecb
        an effort to create a 100% JAXP-compatible Java wrapper for libxml2 and
    Packit 423ecb
        libxslt as part of GNU ClasspathX project.
    Packit 423ecb
      
  • Patrick McPhee provides Rexx bindings fof libxml2 and libxslt, look for
  • Packit 423ecb
        RexxXML.
    Packit 423ecb
      
  • Satimage
  • Packit 423ecb
        provides XMLLib
    Packit 423ecb
        osax. This is an osax for Mac OS X with a set of commands to
    Packit 423ecb
        implement in AppleScript the XML DOM, XPATH and XSLT. Also includes
    Packit 423ecb
        commands for Property-lists (Apple's fast lookup table XML format.)
    Packit 423ecb
      
  • Francesco Montorsi developped wxXml2
  • Packit 423ecb
        wrappers that interface libxml2, allowing wxWidgets applications to
    Packit 423ecb
        load/save/edit XML instances.
    Packit 423ecb

    The distribution includes a set of Python bindings, which are guaranteed

    Packit 423ecb
    to be maintained as part of the library in the future, though the Python
    Packit 423ecb
    interface have not yet reached the completeness of the C API.

    Note that some of the Python purist dislike the default set of Python

    Packit 423ecb
    bindings, rather than complaining I suggest they have a look at lxml the more pythonic bindings for libxml2
    Packit 423ecb
    and libxslt and check the mailing-list.

    Stéphane Bidoul

    Packit 423ecb
    maintains a Windows port
    Packit 423ecb
    of the Python bindings.

    Note to people interested in building bindings, the API is formalized as

    Packit 423ecb
    an XML API description file which allows to
    Packit 423ecb
    automate a large part of the Python bindings, this includes function
    Packit 423ecb
    descriptions, enums, structures, typedefs, etc... The Python script used to
    Packit 423ecb
    build the bindings is python/generator.py in the source distribution.

    To install the Python bindings there are 2 options:

      Packit 423ecb
        
    • If you use an RPM based distribution, simply install the libxml2-python
    • Packit 423ecb
          RPM (and if needed the libxslt-python
      Packit 423ecb
          RPM).
      Packit 423ecb
        
    • Otherwise use the libxml2-python
    • Packit 423ecb
          module distribution corresponding to your installed version of
      Packit 423ecb
          libxml2 and libxslt. Note that to install it you will need both libxml2
      Packit 423ecb
          and libxslt installed and run "python setup.py build install" in the
      Packit 423ecb
          module tree.
      Packit 423ecb

      The distribution includes a set of examples and regression tests for the

      Packit 423ecb
      python bindings in the python/tests directory. Here are some
      Packit 423ecb
      excerpts from those tests:

      tst.py:

      This is a basic test of the file interface and DOM navigation:

      import libxml2, sys
      Packit 423ecb
      Packit 423ecb
      doc = libxml2.parseFile("tst.xml")
      Packit 423ecb
      if doc.name != "tst.xml":
      Packit 423ecb
          print "doc.name failed"
      Packit 423ecb
          sys.exit(1)
      Packit 423ecb
      root = doc.children
      Packit 423ecb
      if root.name != "doc":
      Packit 423ecb
          print "root.name failed"
      Packit 423ecb
          sys.exit(1)
      Packit 423ecb
      child = root.children
      Packit 423ecb
      if child.name != "foo":
      Packit 423ecb
          print "child.name failed"
      Packit 423ecb
          sys.exit(1)
      Packit 423ecb
      doc.freeDoc()

      The Python module is called libxml2; parseFile is the equivalent of

      Packit 423ecb
      xmlParseFile (most of the bindings are automatically generated, and the xml
      Packit 423ecb
      prefix is removed and the casing convention are kept). All node seen at the
      Packit 423ecb
      binding level share the same subset of accessors:

        Packit 423ecb
          
      • name : returns the node name
      • Packit 423ecb
          
      • type : returns a string indicating the node type
      • Packit 423ecb
          
      • content : returns the content of the node, it is based on
      • Packit 423ecb
            xmlNodeGetContent() and hence is recursive.
        Packit 423ecb
          
      • parent , children, last,
      • Packit 423ecb
            next, prev, doc,
        Packit 423ecb
            properties: pointing to the associated element in the tree,
        Packit 423ecb
            those may return None in case no such link exists.
        Packit 423ecb

        Also note the need to explicitly deallocate documents with freeDoc() .

        Packit 423ecb
        Reference counting for libxml2 trees would need quite a lot of work to
        Packit 423ecb
        function properly, and rather than risk memory leaks if not implemented
        Packit 423ecb
        correctly it sounds safer to have an explicit function to free a tree. The
        Packit 423ecb
        wrapper python objects like doc, root or child are them automatically garbage
        Packit 423ecb
        collected.

        validate.py:

        This test check the validation interfaces and redirection of error

        Packit 423ecb
        messages:

        import libxml2
        Packit 423ecb
        Packit 423ecb
        #deactivate error messages from the validation
        Packit 423ecb
        def noerr(ctx, str):
        Packit 423ecb
            pass
        Packit 423ecb
        Packit 423ecb
        libxml2.registerErrorHandler(noerr, None)
        Packit 423ecb
        Packit 423ecb
        ctxt = libxml2.createFileParserCtxt("invalid.xml")
        Packit 423ecb
        ctxt.validate(1)
        Packit 423ecb
        ctxt.parseDocument()
        Packit 423ecb
        doc = ctxt.doc()
        Packit 423ecb
        valid = ctxt.isValid()
        Packit 423ecb
        doc.freeDoc()
        Packit 423ecb
        if valid != 0:
        Packit 423ecb
            print "validity check failed"

        The first thing to notice is the call to registerErrorHandler(), it

        Packit 423ecb
        defines a new error handler global to the library. It is used to avoid seeing
        Packit 423ecb
        the error messages when trying to validate the invalid document.

        The main interest of that test is the creation of a parser context with

        Packit 423ecb
        createFileParserCtxt() and how the behaviour can be changed before calling
        Packit 423ecb
        parseDocument() . Similarly the information resulting from the parsing phase
        Packit 423ecb
        is also available using context methods.

        Contexts like nodes are defined as class and the libxml2 wrappers maps the

        Packit 423ecb
        C function interfaces in terms of objects method as much as possible. The
        Packit 423ecb
        best to get a complete view of what methods are supported is to look at the
        Packit 423ecb
        libxml2.py module containing all the wrappers.

        push.py:

        This test show how to activate the push parser interface:

        import libxml2
        Packit 423ecb
        Packit 423ecb
        ctxt = libxml2.createPushParser(None, "<foo", 4, "test.xml")
        Packit 423ecb
        ctxt.parseChunk("/>", 2, 1)
        Packit 423ecb
        doc = ctxt.doc()
        Packit 423ecb
        Packit 423ecb
        doc.freeDoc()

        The context is created with a special call based on the

        Packit 423ecb
        xmlCreatePushParser() from the C library. The first argument is an optional
        Packit 423ecb
        SAX callback object, then the initial set of data, the length and the name of
        Packit 423ecb
        the resource in case URI-References need to be computed by the parser.

        Then the data are pushed using the parseChunk() method, the last call

        Packit 423ecb
        setting the third argument terminate to 1.

        pushSAX.py:

        this test show the use of the event based parsing interfaces. In this case

        Packit 423ecb
        the parser does not build a document, but provides callback information as
        Packit 423ecb
        the parser makes progresses analyzing the data being provided:

        import libxml2
        Packit 423ecb
        log = ""
        Packit 423ecb
        Packit 423ecb
        class callback:
        Packit 423ecb
            def startDocument(self):
        Packit 423ecb
                global log
        Packit 423ecb
                log = log + "startDocument:"
        Packit 423ecb
        Packit 423ecb
            def endDocument(self):
        Packit 423ecb
                global log
        Packit 423ecb
                log = log + "endDocument:"
        Packit 423ecb
        Packit 423ecb
            def startElement(self, tag, attrs):
        Packit 423ecb
                global log
        Packit 423ecb
                log = log + "startElement %s %s:" % (tag, attrs)
        Packit 423ecb
        Packit 423ecb
            def endElement(self, tag):
        Packit 423ecb
                global log
        Packit 423ecb
                log = log + "endElement %s:" % (tag)
        Packit 423ecb
        Packit 423ecb
            def characters(self, data):
        Packit 423ecb
                global log
        Packit 423ecb
                log = log + "characters: %s:" % (data)
        Packit 423ecb
        Packit 423ecb
            def warning(self, msg):
        Packit 423ecb
                global log
        Packit 423ecb
                log = log + "warning: %s:" % (msg)
        Packit 423ecb
        Packit 423ecb
            def error(self, msg):
        Packit 423ecb
                global log
        Packit 423ecb
                log = log + "error: %s:" % (msg)
        Packit 423ecb
        Packit 423ecb
            def fatalError(self, msg):
        Packit 423ecb
                global log
        Packit 423ecb
                log = log + "fatalError: %s:" % (msg)
        Packit 423ecb
        Packit 423ecb
        handler = callback()
        Packit 423ecb
        Packit 423ecb
        ctxt = libxml2.createPushParser(handler, "<foo", 4, "test.xml")
        Packit 423ecb
        chunk = " url='tst'>b"
        Packit 423ecb
        ctxt.parseChunk(chunk, len(chunk), 0)
        Packit 423ecb
        chunk = "ar</foo>"
        Packit 423ecb
        ctxt.parseChunk(chunk, len(chunk), 1)
        Packit 423ecb
        Packit 423ecb
        reference = "startDocument:startElement foo {'url': 'tst'}:" + \ 
        Packit 423ecb
                    "characters: bar:endElement foo:endDocument:"
        Packit 423ecb
        if log != reference:
        Packit 423ecb
            print "Error got: %s" % log
        Packit 423ecb
            print "Expected: %s" % reference

        The key object in that test is the handler, it provides a number of entry

        Packit 423ecb
        points which can be called by the parser as it makes progresses to indicate
        Packit 423ecb
        the information set obtained. The full set of callback is larger than what
        Packit 423ecb
        the callback class in that specific example implements (see the SAX
        Packit 423ecb
        definition for a complete list). The wrapper will only call those supplied by
        Packit 423ecb
        the object when activated. The startElement receives the names of the element
        Packit 423ecb
        and a dictionary containing the attributes carried by this element.

        Also note that the reference string generated from the callback shows a

        Packit 423ecb
        single character call even though the string "bar" is passed to the parser
        Packit 423ecb
        from 2 different call to parseChunk()

        xpath.py:

        This is a basic test of XPath wrappers support

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

        This test parses a file, then create an XPath context to evaluate XPath

        Packit 423ecb
        expression on it. The xpathEval() method execute an XPath query and returns
        Packit 423ecb
        the result mapped in a Python way. String and numbers are natively converted,
        Packit 423ecb
        and node sets are returned as a tuple of libxml2 Python nodes wrappers. Like
        Packit 423ecb
        the document, the XPath context need to be freed explicitly, also not that
        Packit 423ecb
        the result of the XPath query may point back to the document tree and hence
        Packit 423ecb
        the document must be freed after the result of the query is used.

        xpathext.py:

        This test shows how to extend the XPath engine with functions written in

        Packit 423ecb
        python:

        import libxml2
        Packit 423ecb
        Packit 423ecb
        def foo(ctx, x):
        Packit 423ecb
            return x + 1
        Packit 423ecb
        Packit 423ecb
        doc = libxml2.parseFile("tst.xml")
        Packit 423ecb
        ctxt = doc.xpathNewContext()
        Packit 423ecb
        libxml2.registerXPathFunction(ctxt._o, "foo", None, foo)
        Packit 423ecb
        res = ctxt.xpathEval("foo(1)")
        Packit 423ecb
        if res != 2:
        Packit 423ecb
            print "xpath extension failure"
        Packit 423ecb
        doc.freeDoc()
        Packit 423ecb
        ctxt.xpathFreeContext()

        Note how the extension function is registered with the context (but that

        Packit 423ecb
        part is not yet finalized, this may change slightly in the future).

        tstxpath.py:

        This test is similar to the previous one but shows how the extension

        Packit 423ecb
        function can access the XPath evaluation context:

        def foo(ctx, x):
        Packit 423ecb
            global called
        Packit 423ecb
        Packit 423ecb
            #
        Packit 423ecb
            # test that access to the XPath evaluation contexts
        Packit 423ecb
            #
        Packit 423ecb
            pctxt = libxml2.xpathParserContext(_obj=ctx)
        Packit 423ecb
            ctxt = pctxt.context()
        Packit 423ecb
            called = ctxt.function()
        Packit 423ecb
            return x + 1

        All the interfaces around the XPath parser(or rather evaluation) context

        Packit 423ecb
        are not finalized, but it should be sufficient to do contextual work at the
        Packit 423ecb
        evaluation point.

        Memory debugging:

        last but not least, all tests starts with the following prologue:

        #memory debug specific
        Packit 423ecb
        libxml2.debugMemory(1)

        and ends with the following epilogue:

        #memory debug specific
        Packit 423ecb
        libxml2.cleanupParser()
        Packit 423ecb
        if libxml2.debugMemory(1) == 0:
        Packit 423ecb
            print "OK"
        Packit 423ecb
        else:
        Packit 423ecb
            print "Memory leak %d bytes" % (libxml2.debugMemory(1))
        Packit 423ecb
            libxml2.dumpMemory()

        Those activate the memory debugging interface of libxml2 where all

        Packit 423ecb
        allocated block in the library are tracked. The prologue then cleans up the
        Packit 423ecb
        library state and checks that all allocated memory has been freed. If not it
        Packit 423ecb
        calls dumpMemory() which saves that list in a .memdump file.

        Daniel Veillard

        </body></html>