Blame doc/python.html

Packit Service a31ea6
Packit Service a31ea6
Packit Service a31ea6
<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 Service a31ea6
TD {font-family: Verdana,Arial,Helvetica}
Packit Service a31ea6
BODY {font-family: Verdana,Arial,Helvetica; margin-top: 2em; margin-left: 0em; margin-right: 0em}
Packit Service a31ea6
H1 {font-family: Verdana,Arial,Helvetica}
Packit Service a31ea6
H2 {font-family: Verdana,Arial,Helvetica}
Packit Service a31ea6
H3 {font-family: Verdana,Arial,Helvetica}
Packit Service a31ea6
A:link, A:visited, A:active { text-decoration: underline }
Packit Service a31ea6
</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 Service a31ea6
libxml2, the list below is not exhaustive. Please contact the xml-bindings@gnome.org
Packit Service a31ea6
(archives) in
Packit Service a31ea6
order to get updates to this list or to discuss the specific topic of libxml2
Packit Service a31ea6
or libxslt wrappers or bindings:

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

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

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

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

    Packit Service a31ea6
    to be maintained as part of the library in the future, though the Python
    Packit Service a31ea6
    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 Service a31ea6
    bindings, rather than complaining I suggest they have a look at lxml the more pythonic bindings for libxml2
    Packit Service a31ea6
    and libxslt and check the mailing-list.

    Stéphane Bidoul

    Packit Service a31ea6
    maintains a Windows port
    Packit Service a31ea6
    of the Python bindings.

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

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

    To install the Python bindings there are 2 options:

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

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

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

      tst.py:

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

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

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

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

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

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

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

        validate.py:

        This test check the validation interfaces and redirection of error

        Packit Service a31ea6
        messages:

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

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

        Packit Service a31ea6
        defines a new error handler global to the library. It is used to avoid seeing
        Packit Service a31ea6
        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 Service a31ea6
        createFileParserCtxt() and how the behaviour can be changed before calling
        Packit Service a31ea6
        parseDocument() . Similarly the information resulting from the parsing phase
        Packit Service a31ea6
        is also available using context methods.

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

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

        push.py:

        This test show how to activate the push parser interface:

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

        The context is created with a special call based on the

        Packit Service a31ea6
        xmlCreatePushParser() from the C library. The first argument is an optional
        Packit Service a31ea6
        SAX callback object, then the initial set of data, the length and the name of
        Packit Service a31ea6
        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 Service a31ea6
        setting the third argument terminate to 1.

        pushSAX.py:

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

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

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

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

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

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

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

        xpath.py:

        This is a basic test of XPath wrappers support

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

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

        Packit Service a31ea6
        expression on it. The xpathEval() method execute an XPath query and returns
        Packit Service a31ea6
        the result mapped in a Python way. String and numbers are natively converted,
        Packit Service a31ea6
        and node sets are returned as a tuple of libxml2 Python nodes wrappers. Like
        Packit Service a31ea6
        the document, the XPath context need to be freed explicitly, also not that
        Packit Service a31ea6
        the result of the XPath query may point back to the document tree and hence
        Packit Service a31ea6
        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 Service a31ea6
        python:

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

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

        Packit Service a31ea6
        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 Service a31ea6
        function can access the XPath evaluation context:

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

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

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

        Memory debugging:

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

        #memory debug specific
        Packit Service a31ea6
        libxml2.debugMemory(1)

        and ends with the following epilogue:

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

        Those activate the memory debugging interface of libxml2 where all

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

        Daniel Veillard

        </body></html>