Gnome LogoW3C LogoRed Hat Logo

The XML C library for Gnome

libxml, a.k.a. gnome-xml

Separate documents:

Introduction

This document describes libxml, the XML C library developped for the Gnome project. XML is a standard for building tag-based structured documents/data.

Here are some key points about libxml:

Warning: unless you are forced to because your application links with a Gnome library requiring it, Do Not Use libxml1, use libxml2

Documentation

There are some on-line resources about using libxml:

  1. Check the FAQ
  2. Check the extensive documentation automatically extracted from code comments (using gtk doc).
  3. Look at the documentation about libxml internationalization support
  4. This page provides a global overview and some examples on how to use libxml.
  5. James Henstridge wrote some nice documentation explaining how to use the libxml SAX interface.
  6. George Lebl wrote an article for IBM developerWorks about using libxml.
  7. Check the TODO file
  8. Read the 1.x to 2.x upgrade path. If you are starting a new project using libxml you should really use the 2.x version.
  9. And don't forget to look at the mailing-list archive.

Reporting bugs and getting help

Well, bugs or missing features are always possible, and I will make a point of fixing them in a timely fashion. The best way to report a bug is to use the Gnome bug tracking database (make sure to use the "libxml" module name). I look at reports there regularly and it's good to have a reminder when a bug is still open. Check the instructions on reporting bugs and be sure to specify that the bug is for the package libxml.

There is also a mailing-list xml@gnome.org for libxml, with an on-line archive (old). To subscribe to this list, please visit the associated Web page and follow the instructions. Do not send code, I won't debug it (but patches are really appreciated!).

Check the following too before posting:

Alternatively, you can just send the bug to the xml@gnome.org list; if it's really libxml related I will approve it.. Please do not send me mail directly especially for portability problem, it makes things really harder to track and in some cases I'm not the best person to answer a given question, ask the list instead.

Of course, bugs reported with a suggested patch for fixing them will probably be processed faster.

If you're looking for help, a quick look at the list archive may actually provide the answer, I usually send source samples when answering libxml usage questions. The auto-generated documentantion is not as polished as I would like (i need to learn more about Docbook), but it's a good starting point.

How to help

You can help the project in various ways, the best thing to do first is to subscribe to the mailing-list as explained before, check the archives and the Gnome bug database::

  1. provide patches when you find problems
  2. provide the diffs when you port libxml to a new platform. They may not be integrated in all cases but help pinpointing portability problems and
  3. provide documentation fixes (either as patches to the code comments or as HTML diffs).
  4. provide new documentations pieces (translations, examples, etc ...)
  5. Check the TODO file and try to close one of the items
  6. take one of the points raised in the archive or the bug database and provide a fix. Get in touch with me before to avoid synchronization problems and check that the suggested fix will fit in nicely :-)

Downloads

The latest versions of libxml can be found on xmlsoft.org (Seattle, France) or on the Gnome FTP server either as a source archive or RPM packages. (NOTE that you need both the libxml(2) and libxml(2)-devel packages installed to compile applications using libxml.) Igor Zlatkovic is now the maintainer of the Windows port, he provides binaries

Snapshot:

Contribs:

I do accept external contributions, especially if compiling on another platform, get in touch with me to upload the package. I will keep them in the contrib directory

Libxml is also available from CVS:

News

CVS only : check the Changelog file for a really accurate description

Items floating around but not actively worked on, get in touch with me if you want to test those

2.4.4: Sep 12 2001

2.4.3: Aug 23 2001

2.4.2: Aug 15 2001

2.4.1: July 24 2001

2.4.0: July 10 2001

2.3.14: July 5 2001

2.3.13: June 28 2001

1.8.14: June 28 2001

2.3.12: June 26 2001

2.3.11: June 17 2001

2.3.10: June 1 2001

2.3.9: May 19 2001

Lots of bugfixes, and added a basic SGML catalog support:

1.8.13: May 14 2001

2.3.8: May 3 2001

2.3.7: April 22 2001

2.3.6: April 8 2001

2.3.5: Mar 23 2001

2.3.4: Mar 10 2001

2.3.3: Mar 1 2001

2.3.2: Feb 24 2001

2.3.1: Feb 15 2001

2.3.0: Feb 8 2001 (2.2.12 was on 25 Jan but I didn't kept track)

2.2.11: Jan 4 2001

2.2.10: Nov 25 2000

2.2.9: Nov 25 2000

2.2.8: Nov 13 2000

2.2.7: Oct 31 2000

2.2.6: Oct 25 2000:

2.2.5: Oct 15 2000:

2.2.4: Oct 1 2000:

2.2.3: Sep 17 2000

1.8.10: Sep 6 2000

2.2.2: August 12 2000

2.2.1: July 21 2000

2.2.0: July 14 2000

1.8.9: July 9 2000

2.1.1: July 1 2000

2.1.0 and 1.8.8: June 29 2000

2.0.0: Apr 12 2000

2.0.0beta: Mar 14 2000

1.8.7: Mar 6 2000

1.8.6: Jan 31 2000

1.8.5: Jan 21 2000

1.8.4: Jan 13 2000

1.8.3: Jan 5 2000

1.8.2: Dec 21 1999

1.8.1: Dec 18 1999

1.8.0: Dec 12 1999

1.7.4: Oct 25 1999

1.7.3: Sep 29 1999

1.7.1: Sep 24 1999

1.7.0: sep 23 1999

XML

XML is a standard for markup-based structured documents. Here is an example XML document:

<?xml version="1.0"?>
<EXAMPLE prop1="gnome is great" prop2="&amp; linux too">
  <head>
   <title>Welcome to Gnome</title>
  </head>
  <chapter>
   <title>The Linux adventure</title>
   <p>bla bla bla ...</p>
   <image href="linus.gif"/>
   <p>...</p>
  </chapter>
</EXAMPLE>

The first line specifies that it's an XML document and gives useful information about its encoding. Then the document is a text format whose structure is specified by tags between brackets. Each tag opened has to be closed. XML is pedantic about this. However, if a tag is empty (no content), a single tag can serve as both the opening and closing tag if it ends with /> rather than with >. Note that, for example, the image tag has no content (just an attribute) and is closed by ending the tag with />.

XML can be applied sucessfully to a wide range of uses, from long term structured document maintenance (where it follows the steps of SGML) to simple data encoding mechanisms like configuration file formatting (glade), spreadsheets (gnumeric), or even shorter lived documents such as WebDAV where it is used to encode remote calls between a client and a server.

XSLT

Check the separate libxslt page

XSL Transformations, is a language for transforming XML documents into other XML documents (or HTML/textual output).

A separate library called libxslt is being built on top of libxml2. This module "libxslt" can be found in the Gnome CVS base too.

You can check the features supported and the progresses on the Changelog

An overview of libxml architecture

Libxml is made of multiple components; some of them are optional, and most of the block interfaces are public. The main components are:

Graphically this gives the following:

a graphical view of the various

The tree output

The parser returns a tree built during the document analysis. The value returned is an xmlDocPtr (i.e., a pointer to an xmlDoc structure). This structure contains information such as the file name, the document type, and a children pointer which is the root of the document (or more exactly the first child under the root which is the document). The tree is made of xmlNodes, chained in double-linked lists of siblings and with a children<->parent relationship. An xmlNode can also carry properties (a chain of xmlAttr structures). An attribute may have a value which is a list of TEXT or ENTITY_REF nodes.

Here is an example (erroneous with respect to the XML spec since there should be only one ELEMENT under the root):

 structure.gif

In the source package there is a small program (not installed by default) called xmllint which parses XML files given as argument and prints them back as parsed. This is useful for detecting errors both in XML code and in the XML parser itself. It has an option --debug which prints the actual in-memory structure of the document; here is the result with the example given before:

DOCUMENT
version=1.0
standalone=true
  ELEMENT EXAMPLE
    ATTRIBUTE prop1
      TEXT
      content=gnome is great
    ATTRIBUTE prop2
      ENTITY_REF
      TEXT
      content= linux too 
    ELEMENT head
      ELEMENT title
        TEXT
        content=Welcome to Gnome
    ELEMENT chapter
      ELEMENT title
        TEXT
        content=The Linux adventure
      ELEMENT p
        TEXT
        content=bla bla bla ...
      ELEMENT image
        ATTRIBUTE href
          TEXT
          content=linus.gif
      ELEMENT p
        TEXT
        content=...

This should be useful for learning the internal representation model.

The SAX interface

Sometimes the DOM tree output is just too large to fit reasonably into memory. In that case (and if you don't expect to save back the XML document loaded using libxml), it's better to use the SAX interface of libxml. SAX is a callback-based interface to the parser. Before parsing, the application layer registers a customized set of callbacks which are called by the library as it progresses through the XML input.

To get more detailed step-by-step guidance on using the SAX interface of libxml, see the nice documentation.written by James Henstridge.

You can debug the SAX behaviour by using the testSAX program located in the gnome-xml module (it's usually not shipped in the binary packages of libxml, but you can find it in the tar source distribution). Here is the sequence of callbacks that would be reported by testSAX when parsing the example XML document shown earlier:

SAX.setDocumentLocator()
SAX.startDocument()
SAX.getEntity(amp)
SAX.startElement(EXAMPLE, prop1='gnome is great', prop2='&amp; linux too')
SAX.characters(   , 3)
SAX.startElement(head)
SAX.characters(    , 4)
SAX.startElement(title)
SAX.characters(Welcome to Gnome, 16)
SAX.endElement(title)
SAX.characters(   , 3)
SAX.endElement(head)
SAX.characters(   , 3)
SAX.startElement(chapter)
SAX.characters(    , 4)
SAX.startElement(title)
SAX.characters(The Linux adventure, 19)
SAX.endElement(title)
SAX.characters(    , 4)
SAX.startElement(p)
SAX.characters(bla bla bla ..., 15)
SAX.endElement(p)
SAX.characters(    , 4)
SAX.startElement(image, href='linus.gif')
SAX.endElement(image)
SAX.characters(    , 4)
SAX.startElement(p)
SAX.characters(..., 3)
SAX.endElement(p)
SAX.characters(   , 3)
SAX.endElement(chapter)
SAX.characters( , 1)
SAX.endElement(EXAMPLE)
SAX.endDocument()

Most of the other interfaces of libxml are based on the DOM tree-building facility, so nearly everything up to the end of this document presupposes the use of the standard DOM tree build. Note that the DOM tree itself is built by a set of registered default callbacks, without internal specific interface.

The XML library interfaces

This section is directly intended to help programmers getting bootstrapped using the XML library from the C language. It is not intended to be extensive. I hope the automatically generated documents will provide the completeness required, but as a separate set of documents. The interfaces of the XML library are by principle low level, there is nearly zero abstraction. Those interested in a higher level API should look at DOM.

The parser interfaces for XML are separated from the HTML parser interfaces. Let's have a look at how the XML parser can be called:

Invoking the parser : the pull method

Usually, the first thing to do is to read an XML input. The parser accepts documents either from in-memory strings or from files. The functions are defined in "parser.h":

xmlDocPtr xmlParseMemory(char *buffer, int size);

Parse a null-terminated string containing the document.

xmlDocPtr xmlParseFile(const char *filename);

Parse an XML document contained in a (possibly compressed) file.

The parser returns a pointer to the document structure (or NULL in case of failure).

Invoking the parser: the push method

In order for the application to keep the control when the document is being fetched (which is common for GUI based programs) libxml provides a push interface, too, as of version 1.8.3. Here are the interface functions:

xmlParserCtxtPtr xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax,
                                         void *user_data,
                                         const char *chunk,
                                         int size,
                                         const char *filename);
int              xmlParseChunk          (xmlParserCtxtPtr ctxt,
                                         const char *chunk,
                                         int size,
                                         int terminate);

and here is a simple example showing how to use the interface:

            FILE *f;

            f = fopen(filename, "r");
            if (f != NULL) {
                int res, size = 1024;
                char chars[1024];
                xmlParserCtxtPtr ctxt;

                res = fread(chars, 1, 4, f);
                if (res > 0) {
                    ctxt = xmlCreatePushParserCtxt(NULL, NULL,
                                chars, res, filename);
                    while ((res = fread(chars, 1, size, f)) > 0) {
                        xmlParseChunk(ctxt, chars, res, 0);
                    }
                    xmlParseChunk(ctxt, chars, 0, 1);
                    doc = ctxt->myDoc;
                    xmlFreeParserCtxt(ctxt);
                }
            }

The HTML parser embedded into libxml also has a push interface; the functions are just prefixed by "html" rather than "xml".

Invoking the parser: the SAX interface

The tree-building interface makes the parser memory-hungry, first loading the document in memory and then building the tree itself. Reading a document without building the tree is possible using the SAX interfaces (see SAX.h and James Henstridge's documentation). Note also that the push interface can be limited to SAX: just use the two first arguments of xmlCreatePushParserCtxt().

Building a tree from scratch

The other way to get an XML tree in memory is by building it. Basically there is a set of functions dedicated to building new elements. (These are also described in <libxml/tree.h>.) For example, here is a piece of code that produces the XML document used in the previous examples:

    #include <libxml/tree.h>
    xmlDocPtr doc;
    xmlNodePtr tree, subtree;

    doc = xmlNewDoc("1.0");
    doc->children = xmlNewDocNode(doc, NULL, "EXAMPLE", NULL);
    xmlSetProp(doc->children, "prop1", "gnome is great");
    xmlSetProp(doc->children, "prop2", "& linux too");
    tree = xmlNewChild(doc->children, NULL, "head", NULL);
    subtree = xmlNewChild(tree, NULL, "title", "Welcome to Gnome");
    tree = xmlNewChild(doc->children, NULL, "chapter", NULL);
    subtree = xmlNewChild(tree, NULL, "title", "The Linux adventure");
    subtree = xmlNewChild(tree, NULL, "p", "bla bla bla ...");
    subtree = xmlNewChild(tree, NULL, "image", NULL);
    xmlSetProp(subtree, "href", "linus.gif");

Not really rocket science ...

Traversing the tree

Basically by including "tree.h" your code has access to the internal structure of all the elements of the tree. The names should be somewhat simple like parent, children, next, prev, properties, etc... For example, still with the previous example:

doc->children->children->children

points to the title element,

doc->children->children->next->children->children

points to the text node containing the chapter title "The Linux adventure".

NOTE: XML allows PIs and comments to be present before the document root, so doc->children may point to an element which is not the document Root Element; a function xmlDocGetRootElement() was added for this purpose.

Modifying the tree

Functions are provided for reading and writing the document content. Here is an excerpt from the tree API:

xmlAttrPtr xmlSetProp(xmlNodePtr node, const xmlChar *name, const xmlChar *value);

This sets (or changes) an attribute carried by an ELEMENT node. The value can be NULL.

const xmlChar *xmlGetProp(xmlNodePtr node, const xmlChar *name);

This function returns a pointer to new copy of the property content. Note that the user must deallocate the result.

Two functions are provided for reading and writing the text associated with elements:

xmlNodePtr xmlStringGetNodeList(xmlDocPtr doc, const xmlChar *value);

This function takes an "external" string and converts it to one text node or possibly to a list of entity and text nodes. All non-predefined entity references like &Gnome; will be stored internally as entity nodes, hence the result of the function may not be a single node.

xmlChar *xmlNodeListGetString(xmlDocPtr doc, xmlNodePtr list, int inLine);

This function is the inverse of xmlStringGetNodeList(). It generates a new string containing the content of the text and entity nodes. Note the extra argument inLine. If this argument is set to 1, the function will expand entity references. For example, instead of returning the &Gnome; XML encoding in the string, it will substitute it with its value (say, "GNU Network Object Model Environment").

Saving a tree

Basically 3 options are possible:

void xmlDocDumpMemory(xmlDocPtr cur, xmlChar**mem, int *size);

Returns a buffer into which the document has been saved.

extern void xmlDocDump(FILE *f, xmlDocPtr doc);

Dumps a document to an open file descriptor.

int xmlSaveFile(const char *filename, xmlDocPtr cur);

Saves the document to a file. In this case, the compression interface is triggered if it has been turned on.

Compression

The library transparently handles compression when doing file-based accesses. The level of compression on saves can be turned on either globally or individually for one file:

int xmlGetDocCompressMode (xmlDocPtr doc);

Gets the document compression ratio (0-9).

void xmlSetDocCompressMode (xmlDocPtr doc, int mode);

Sets the document compression ratio.

int xmlGetCompressMode(void);

Gets the default compression ratio.

void xmlSetCompressMode(int mode);

Sets the default compression ratio.

Entities or no entities

Entities in principle are similar to simple C macros. An entity defines an abbreviation for a given string that you can reuse many times throughout the content of your document. Entities are especially useful when a given string may occur frequently within a document, or to confine the change needed to a document to a restricted area in the internal subset of the document (at the beginning). Example:

1 <?xml version="1.0"?>
2 <!DOCTYPE EXAMPLE SYSTEM "example.dtd" [
3 <!ENTITY xml "Extensible Markup Language">
4 ]>
5 <EXAMPLE>
6    &xml;
7 </EXAMPLE>

Line 3 declares the xml entity. Line 6 uses the xml entity, by prefixing its name with '&' and following it by ';' without any spaces added. There are 5 predefined entities in libxml allowing you to escape charaters with predefined meaning in some parts of the xml document content: &lt; for the character '<', &gt; for the character '>', &apos; for the character ''', &quot; for the character '"', and &amp; for the character '&'.

One of the problems related to entities is that you may want the parser to substitute an entity's content so that you can see the replacement text in your application. Or you may prefer to keep entity references as such in the content to be able to save the document back without losing this usually precious information (if the user went through the pain of explicitly defining entities, he may have a a rather negative attitude if you blindly susbtitute them as saving time). The xmlSubstituteEntitiesDefault() function allows you to check and change the behaviour, which is to not substitute entities by default.

Here is the DOM tree built by libxml for the previous document in the default case:

/gnome/src/gnome-xml -> ./xmllint --debug test/ent1
DOCUMENT
version=1.0
   ELEMENT EXAMPLE
     TEXT
     content=
     ENTITY_REF
       INTERNAL_GENERAL_ENTITY xml
       content=Extensible Markup Language
     TEXT
     content=

And here is the result when substituting entities:

/gnome/src/gnome-xml -> ./tester --debug --noent test/ent1
DOCUMENT
version=1.0
   ELEMENT EXAMPLE
     TEXT
     content=     Extensible Markup Language

So, entities or no entities? Basically, it depends on your use case. I suggest that you keep the non-substituting default behaviour and avoid using entities in your XML document or data if you are not willing to handle the entity references elements in the DOM tree.

Note that at save time libxml enforces the conversion of the predefined entities where necessary to prevent well-formedness problems, and will also transparently replace those with chars (i.e. it will not generate entity reference elements in the DOM tree or call the reference() SAX callback when finding them in the input).

WARNING: handling entities on top of the libxml SAX interface is difficult!!! If you plan to use non-predefined entities in your documents, then the learning cuvre to handle then using the SAX API may be long. If you plan to use complex documents, I strongly suggest you consider using the DOM interface instead and let libxml deal with the complexity rather than trying to do it yourself.

Namespaces

The libxml library implements XML namespaces support by recognizing namespace contructs in the input, and does namespace lookup automatically when building the DOM tree. A namespace declaration is associated with an in-memory structure and all elements or attributes within that namespace point to it. Hence testing the namespace is a simple and fast equality operation at the user level.

I suggest that people using libxml use a namespace, and declare it in the root element of their document as the default namespace. Then they don't need to use the prefix in the content but we will have a basis for future semantic refinement and merging of data from different sources. This doesn't increase the size of the XML output significantly, but significantly increases its value in the long-term. Example:

<mydoc xmlns="http://mydoc.example.org/schemas/">
   <elem1>...</elem1>
   <elem2>...</elem2>
</mydoc>

The namespace value has to be an absolute URL, but the URL doesn't have to point to any existing resource on the Web. It will bind all the element and atributes with that URL. I suggest to use an URL within a domain you control, and that the URL should contain some kind of version information if possible. For example, "http://www.gnome.org/gnumeric/1.0/" is a good namespace scheme.

Then when you load a file, make sure that a namespace carrying the version-independent prefix is installed on the root element of your document, and if the version information don't match something you know, warn the user and be liberal in what you accept as the input. Also do *not* try to base namespace checking on the prefix value. <foo:text> may be exactly the same as <bar:text> in another document. What really matters is the URI associated with the element or the attribute, not the prefix string (which is just a shortcut for the full URI). In libxml, element and attributes have an ns field pointing to an xmlNs structure detailing the namespace prefix and its URI.

@@Interfaces@@

@@Examples@@

Usually people object to using namespaces together with validity checking. I will try to make sure that using namespaces won't break validity checking, so even if you plan to use or currently are using validation I strongly suggest adding namespaces to your document. A default namespace scheme xmlns="http://...." should not break validity even on less flexible parsers. Using namespaces to mix and differentiate content coming from multiple DTDs will certainly break current validation schemes. I will try to provide ways to do this, but this may not be portable or standardized.

Validation, or are you afraid of DTDs ?

Well what is validation and what is a DTD ?

Validation is the process of checking a document against a set of construction rules; a DTD (Document Type Definition) is such a set of rules.

The validation process and building DTDs are the two most difficult parts of the XML life cycle. Briefly a DTD defines all the possibles element to be found within your document, what is the formal shape of your document tree (by defining the allowed content of an element, either text, a regular expression for the allowed list of children, or mixed content i.e. both text and children). The DTD also defines the allowed attributes for all elements and the types of the attributes. For more detailed information, I suggest that you read the related parts of the XML specification, the examples found under gnome-xml/test/valid/dtd and any of the large number of books available on XML. The dia example in gnome-xml/test/valid should be both simple and complete enough to allow you to build your own.

A word of warning, building a good DTD which will fit the needs of your application in the long-term is far from trivial; however, the extra level of quality it can ensure is well worth the price for some sets of applications or if you already have already a DTD defined for your application field.

The validation is not completely finished but in a (very IMHO) usable state. Until a real validation interface is defined the way to do it is to define and set the xmlDoValidityCheckingDefaultValue external variable to 1, this will of course be changed at some point:

extern int xmlDoValidityCheckingDefaultValue;

...

xmlDoValidityCheckingDefaultValue = 1;

To handle external entities, use the function xmlSetExternalEntityLoader(xmlExternalEntityLoader f); to link in you HTTP/FTP/Entities database library to the standard libxml core.

@@interfaces@@

DOM Principles

DOM stands for the Document Object Model; this is an API for accessing XML or HTML structured documents. Native support for DOM in Gnome is on the way (module gnome-dom), and will be based on gnome-xml. This will be a far cleaner interface to manipulate XML files within Gnome since it won't expose the internal structure.

The current DOM implementation on top of libxml is the gdome2 Gnome module, this is a full DOM interface, thanks to Paolo Casarini, check the Gdome2 homepage for more informations.

A real example

Here is a real size example, where the actual content of the application data is not kept in the DOM tree but uses internal structures. It is based on a proposal to keep a database of jobs related to Gnome, with an XML based storage structure. Here is an XML encoded jobs base:

<?xml version="1.0"?>
<gjob:Helping xmlns:gjob="http://www.gnome.org/some-location">
  <gjob:Jobs>

    <gjob:Job>
      <gjob:Project ID="3"/>
      <gjob:Application>GBackup</gjob:Application>
      <gjob:Category>Development</gjob:Category>

      <gjob:Update>
        <gjob:Status>Open</gjob:Status>
        <gjob:Modified>Mon, 07 Jun 1999 20:27:45 -0400 MET DST</gjob:Modified>
        <gjob:Salary>USD 0.00</gjob:Salary>
      </gjob:Update>

      <gjob:Developers>
        <gjob:Developer>
        </gjob:Developer>
      </gjob:Developers>

      <gjob:Contact>
        <gjob:Person>Nathan Clemons</gjob:Person>
        <gjob:Email>nathan@windsofstorm.net</gjob:Email>
        <gjob:Company>
        </gjob:Company>
        <gjob:Organisation>
        </gjob:Organisation>
        <gjob:Webpage>
        </gjob:Webpage>
        <gjob:Snailmail>
        </gjob:Snailmail>
        <gjob:Phone>
        </gjob:Phone>
      </gjob:Contact>

      <gjob:Requirements>
      The program should be released as free software, under the GPL.
      </gjob:Requirements>

      <gjob:Skills>
      </gjob:Skills>

      <gjob:Details>
      A GNOME based system that will allow a superuser to configure 
      compressed and uncompressed files and/or file systems to be backed 
      up with a supported media in the system.  This should be able to 
      perform via find commands generating a list of files that are passed 
      to tar, dd, cpio, cp, gzip, etc., to be directed to the tape machine 
      or via operations performed on the filesystem itself. Email 
      notification and GUI status display very important.
      </gjob:Details>

    </gjob:Job>

  </gjob:Jobs>
</gjob:Helping>

While loading the XML file into an internal DOM tree is a matter of calling only a couple of functions, browsing the tree to gather the ata and generate the internal structures is harder, and more error prone.

The suggested principle is to be tolerant with respect to the input structure. For example, the ordering of the attributes is not significant, the XML specification is clear about it. It's also usually a good idea not to depend on the order of the children of a given node, unless it really makes things harder. Here is some code to parse the information for a person:

/*
 * A person record
 */
typedef struct person {
    char *name;
    char *email;
    char *company;
    char *organisation;
    char *smail;
    char *webPage;
    char *phone;
} person, *personPtr;

/*
 * And the code needed to parse it
 */
personPtr parsePerson(xmlDocPtr doc, xmlNsPtr ns, xmlNodePtr cur) {
    personPtr ret = NULL;

DEBUG("parsePerson\n");
    /*
     * allocate the struct
     */
    ret = (personPtr) malloc(sizeof(person));
    if (ret == NULL) {
        fprintf(stderr,"out of memory\n");
        return(NULL);
    }
    memset(ret, 0, sizeof(person));

    /* We don't care what the top level element name is */
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        if ((!strcmp(cur->name, "Person")) && (cur->ns == ns))
            ret->name = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
        if ((!strcmp(cur->name, "Email")) && (cur->ns == ns))
            ret->email = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
        cur = cur->next;
    }

    return(ret);
}

Here are a couple of things to notice:

Here is another piece of code used to parse another level of the structure:

#include <libxml/tree.h>
/*
 * a Description for a Job
 */
typedef struct job {
    char *projectID;
    char *application;
    char *category;
    personPtr contact;
    int nbDevelopers;
    personPtr developers[100]; /* using dynamic alloc is left as an exercise */
} job, *jobPtr;

/*
 * And the code needed to parse it
 */
jobPtr parseJob(xmlDocPtr doc, xmlNsPtr ns, xmlNodePtr cur) {
    jobPtr ret = NULL;

DEBUG("parseJob\n");
    /*
     * allocate the struct
     */
    ret = (jobPtr) malloc(sizeof(job));
    if (ret == NULL) {
        fprintf(stderr,"out of memory\n");
        return(NULL);
    }
    memset(ret, 0, sizeof(job));

    /* We don't care what the top level element name is */
    cur = cur->xmlChildrenNode;
    while (cur != NULL) {
        
        if ((!strcmp(cur->name, "Project")) && (cur->ns == ns)) {
            ret->projectID = xmlGetProp(cur, "ID");
            if (ret->projectID == NULL) {
                fprintf(stderr, "Project has no ID\n");
            }
        }
        if ((!strcmp(cur->name, "Application")) && (cur->ns == ns))
            ret->application = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
        if ((!strcmp(cur->name, "Category")) && (cur->ns == ns))
            ret->category = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
        if ((!strcmp(cur->name, "Contact")) && (cur->ns == ns))
            ret->contact = parsePerson(doc, ns, cur);
        cur = cur->next;
    }

    return(ret);
}

Once you are used to it, writing this kind of code is quite simple, but boring. Ultimately, it could be possble to write stubbers taking either C data structure definitions, a set of XML examples or an XML DTD and produce the code needed to import and export the content between C data and XML storage. This is left as an exercise to the reader :-)

Feel free to use the code for the full C parsing example as a template, it is also available with Makefile in the Gnome CVS base under gnome-xml/example

Contributions

Daniel Veillard

$Id: xml.html,v 1.108 2001/08/24 00:49:01 veillard Exp $