libxml2

From Wikipedia, the free encyclopedia

libxml2
Initial release September 23, 1999
Written in C
OS Unix-like, Windows, CygWin, Mac OS, RISC OS, OS/2, VMS, QNX, MVS...
Genre XML parser
License MIT License
Website xmlsoft.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.

Contents

[edit] Usage examples

[edit] Sample XML document

<?xml version="1.0" encoding="UTF-8"?>
<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 1
        ...
    </array>
</data>

[edit] 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] );
        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, (const xmlChar *)"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 );
 
    return 0;
}

[edit] External links

Languages