Jump to content

libxml2

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Joachim Wuttke (talk | contribs) at 16:11, 13 April 2007 (+ usage example). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.


libxml2
Repository
Operating systemUnix-like, Windows, CygWin, MacOS, RISC Os, OS/2, VMS, QNX, MVS...
TypeXML parser
LicenseMIT License
Websitexmlsoft.org


libXML is a library for parsing XML documents. It is written in the C programming language, and provides bindings to other languages. It was originally developed for the GNOME project, but can be used outside it. The libXML code is highly portable and is released under the MIT license. The current version is 2.6.27.

Compared to similar projects, libXML has a relatively complete and accessible documentation. It has even a useful tutorial, even if this still uses version 1 style.

Usage examples

Sample XML document

<data contents="a very simple XML sample document">
    <array name="Fibonacci">
        1 1 2 3 5 8 13 21 34 55 ...
    </array>
    <array name="Pascal">
        1
        1 1
        1 2 1
        1 3 3 6
        ...
    </array>
</data>

Sample parser in C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>

/*
    Parse a simple XML document, using libxml2

    Document syntax:
       <data>{<array name="[text]">[text]</array>|[text]}</data>
*/

int main( int argc, char **argv ){

    xmlChar *txt;
    xmlDocPtr doc;
    xmlNodePtr cur, sub;
		
    if (argc <= 1) {
        printf( "Usage: %s docname\n", argv[0] );
        xmlFreeDoc( doc );
        return( -1 );
    }

    if( !(doc = xmlParseFile( argv[1] ) ) ){
        fprintf( stderr, "Document not parsed successfully.\n" );
        xmlFreeDoc( doc );
        return( -1 );
    }
	
    if( !(cur = xmlDocGetRootElement( doc ) ) ){
        fprintf( stderr, "Document has no root element.\n" );
        xmlFreeDoc( doc );
        return( -1 );
    }
    if( xmlStrcmp( cur->name, (const xmlChar *) "data" ) ){
        fprintf( stderr, "Document of the wrong type, root node != data\n" );
        xmlFreeDoc( doc );
        return( -1 );
    }
	
    sub = cur->children;
    while( sub != NULL ){
        if( (!xmlStrcmp(sub->name, (const xmlChar *)"array" ) ) ){
            txt = xmlGetProp( sub, "name" );
            printf( "array %s:\n", txt );
            xmlFree( txt );
            txt = xmlNodeListGetString( doc, sub->children, 1 );
            printf( "%s\n", txt );
            xmlFree( txt );
        }
	sub = sub->next;
    }
	
    xmlFreeDoc( doc );
}

External link