Whole document tree
    

Whole document tree

The XML library for Gnome

The XML library for Gnome

libxml, a.k.a. gnome-xml

Note: this is a GNOME 1.x branch of libxml, this should not be used for developping new applications unless forced by binary compatibility constraints. Check the main web page to retrieve the most recent version.

Introduction

This document describes libxml, the XML library provided in the Gnome framework. XML is a standard for building tag-based structured documents/data.

Here are some key points about libxml:

  • The internal document repesentation is as close as possible to the DOM interfaces.
  • Libxml also has a SAX like interface; the interface is designed to be compatible with Expat.
  • Libxml now includes a nearly complete XPath implementation.
  • Libxml exports Push and Pull type parser interfaces for both XML and HTML.
  • This library is released both under the W3C Copyright and the GNU LGPL. Basically, everybody should be happy; if not, drop me a mail.
  • There is a first set of instruction concerning upgrade from libxml-1.x to libxml-2.x

Documentation

There are some on-line resources about using libxml:

  1. The code is commented in a way which allows extensive documentation to be automatically extracted.
  2. This page provides a global overview and some examples on how to use libxml.
  3. James Henstridge wrote some nice documentation explaining how to use the libxml SAX interface.
  4. George Lebl wrote an article for IBM developerWorks about using libxml.
  5. It is also a good idea to check to Raph Levien web site since he is building the DOM interface gdome on top of libxml result tree and an implementation of SVG called gill. Check his DOMination paper.
  6. And don't forget to look at the mailing-list archive, too.

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. 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 gnome-xml.

There is also a mailing-list xml@rufus.w3.org for libxml, with an on-line archive. To subscribe to this majordomo based list, send a mail message to majordomo@rufus.w3.org with "subscribe xml" in the content of the message.

Alternatively, you can just send the bug to the xml@rufus.w3.org list.

Downloads

The latest versions of libxml can be found on rpmfind.net or on the Gnome FTP server either as a source archive or RPMs packages. (NOTE that you need both the libxml and libxml-devel packages installed to compile applications using libxml.)

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 2 CVs bases:

  • The W3C CVS base, available read-only using the CVS pserver authentification (I tend to use this base for my own development, so it's updated more regularly, but the content may not be as stable):

    CVSROOT=:pserver:anonymous@dev.w3.org:/sources/public
        password: anonymous
        module: XML
  • The Gnome CVS base. Check the Gnome CVS Tools page; the CVS module is gnome-xml.

News

CVS only : check the Changelog file for really accurate description

  • working on HTML and XML links recognition layers, get in touch with me if you want to test those.
  • huge work toward libxml-2.0: This work is available only in W3C CVs base for the moment. You get the snapshot for the updated version:
    • fix I18N support. ISO-Latin-x/UTF-8/UTF-16 seems correctly handled now
    • Better handling of entities, especially well formedness checking and proper PEref extensions in external subsets
    • DTD conditional sections
    • Validation now correcly handle entities content
    • change structures to accomodate DOM
    • Lot of work toward a better compliance. I'm now running and debugging regression tests agains the OASIS testsuite

1.8.12: May 4 2001

  • integated the new libxml2 XML parser and made it available through xmlUseNewParser()
  • fixed a number of tests case
  • upgraded the tester program
  • a few bug fixes on the default old parser too.

1.8.10: Sep 6 2000

  • bug fix release for some Gnome projects

1.8.7: Mar 6 2000

  • This is a bug fix release:
  • It is possible to disable the ignorable blanks heuristic used by libxml-1.x, a new function xmlKeepBlanksDefault(0) will allow this. Note that for adherence to XML spec, this behaviour will be disabled by default in 2.x . The same function will allow to keep compatibility for old code.
  • Blanks in <a> </a> constructs are not ignored anymore, avoiding heuristic is really the Right Way :-\
  • The unchecked use of snprintf which was breaking libxml-1.8.6 compilation on some platforms has been fixed
  • nanoftp.c nanohttp.c: Fixed '#' and '?' stripping when processing URIs

1.8.6: Jan 31 2000

  • added a nanoFTP transport module, debugged until the new version of rpmfind can use it without troubles

1.8.5: Jan 21 2000

  • adding APIs to parse a well balanced chunk of XML (production [43] content of the XML spec)
  • fixed a hideous bug in xmlGetProp pointed by Rune.Djurhuus@fast.no
  • Jody Goldberg <jgoldberg@home.com> provided another patch trying to solve the zlib checks problems
  • The current state in gnome CVS base is expected to ship as 1.8.5 with gnumeric soon

1.8.4: Jan 13 2000

  • bug fixes, reintroduced xmlNewGlobalNs(), fixed xmlNewNs()
  • all exit() call should have been removed from libxml
  • fixed a problem with INCLUDE_WINSOCK on WIN32 platform
  • added newDocFragment()

1.8.3: Jan 5 2000

  • a Push interface for the XML and HTML parsers
  • a shell-like interface to the document tree (try tester --shell :-)
  • lots of bug fixes and improvement added over XMas hollidays
  • fixed the DTD parsing code to work with the xhtml DTD
  • added xmlRemoveProp(), xmlRemoveID() and xmlRemoveRef()
  • Fixed bugs in xmlNewNs()
  • External entity loading code has been revamped, now it uses xmlLoadExternalEntity(), some fix on entities processing were added
  • cleaned up WIN32 includes of socket stuff

1.8.2: Dec 21 1999

  • I got another problem with includes and C++, I hope this issue is fixed for good this time
  • Added a few tree modification functions: xmlReplaceNode, xmlAddPrevSibling, xmlAddNextSibling, xmlNodeSetName and xmlDocSetRootElement
  • Tried to improve the HTML output with help from Chris Lahey

1.8.1: Dec 18 1999

  • various patches to avoid troubles when using libxml with C++ compilers the "namespace" keyword and C escaping in include files
  • a problem in one of the core macros IS_CHAR was corrected
  • fixed a bug introduced in 1.8.0 breaking default namespace processing, and more specifically the Dia application
  • fixed a posteriori validation (validation after parsing, or by using a Dtd not specified in the original document)
  • fixed a bug in

1.8.0: Dec 12 1999

  • cleanup, especially memory wise
  • the parser should be more reliable, especially the HTML one, it should not crash, whatever the input !
  • Integrated various patches, especially a speedup improvement for large dataset from Carl Nygard, configure with --with-buffers to enable them.
  • attribute normalization, oops should have been added long ago !
  • attributes defaulted from Dtds should be available, xmlSetProp() now does entities escapting by default.

1.7.4: Oct 25 1999

  • Lots of HTML improvement
  • Fixed some errors when saving both XML and HTML
  • More examples, the regression tests should now look clean
  • Fixed a bug with contiguous charref

1.7.3: Sep 29 1999

  • portability problems fixed
  • snprintf was used unconditionnally, leading to link problems on system were it's not available, fixed

1.7.1: Sep 24 1999

  • The basic type for strings manipulated by libxml has been renamed in 1.7.1 from CHAR to xmlChar. The reason is that CHAR was conflicting with a predefined type on Windows. However on non WIN32 environment, compatibility is provided by the way of a #define .
  • Changed another error : the use of a structure field called errno, and leading to troubles on platforms where it's a macro

1.7.0: sep 23 1999

  • Added the ability to fetch remote DTD or parsed entities, see the nanohttp module.
  • Added an errno to report errors by another mean than a simple printf like callback
  • Finished ID/IDREF support and checking when validation
  • Serious memory leaks fixed (there is now a memory wrapper module)
  • Improvement of XPath implementation
  • Added an HTML parser front-end

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.

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 root 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 childs<->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 tester 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 href="http://www.daa.com.au/~james/gnome/xml-sax/xml-sax.html">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 functionalities 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 been 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);
                }
            }

Also note that 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

A couple of comments can be made, first this mean that the parser is memory-hungry, first to load the document in memory, second to build the tree. 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 "tree.h".) For example, here is a piece of code that produces the XML document used in the previous examples:

    xmlDocPtr doc;
    xmlNodePtr tree, subtree;

    doc = xmlNewDoc("1.0");
    doc->root = xmlNewDocNode(doc, NULL, "EXAMPLE", NULL);
    xmlSetProp(doc->root, "prop1", "gnome is great");
    xmlSetProp(doc->root, "prop2", "& linux too");
    tree = xmlNewChild(doc->root, NULL, "head", NULL);
    subtree = xmlNewChild(tree, NULL, "title", "Welcome to Gnome");
    tree = xmlNewChild(doc->root, 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, childs, next, prev, properties, etc... For example, still with the previous example:

doc->root->childs->childs

points to the title element,

doc->root->childs->next->child->child

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->root 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 the property content. Note that no extra copy is made.

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 convert 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"). Set this argument if you want to use the string for non-XML usage like User Interface.

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 it's 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 -> ./tester --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 enforce 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).

Namespaces

The libxml library implements namespace @@ 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 augment significantly the size of the XML output, but significantly increase its value in the long-term.

Concerning the namespace value, this has to be an URL, but the URL doesn't have to point to any existing resource on the Web. I suggest that it makes sense 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 matter is the URI associated with the element or the attribute, not the prefix string (which is just a shortcut for the full URI).

@@Interfaces@@

@@Examples@@

Usually people object using namespace in the case of validation, I object this and will make sure that using namespaces won't break validity checking, so even is 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. Now using namespace 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 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 childs). The DTD also defines the allowed attributes for all elements and the types of the attributes. For more detailed informations, I suggest to read the related parts of the XML specification, the examples found under gnome-xml/test/valid/dtd and the large amount 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 your needs of your application in the long-term is far from trivial, however the extra level of quality it can insure 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 it 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. DOM defines a set of IDL (or Java) interfaces allowing to traverse and manipulate a document. The DOM library will allow accessing and modifying "live" documents presents on other programs like this:

 DOM.gif

This should help greatly doing things like modifying a gnumeric spreadsheet embedded in a GWP document for example.

The current DOM implementation on top of libxml is the gdome Gnome module, this is a full DOM interface, thanks to Raph Levien.

The gnome-dom module in the Gnome CVS base is obsolete

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 informations and generate the internals 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, Cthe XML specification is clear about it. It's also usually a good idea to not be dependent of the orders of the childs of a given node, unless it really makes things harder. Here is some code to parse the informations 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->childs;
    while (cur != NULL) {
        if ((!strcmp(cur->name, "Person")) && (cur->ns == ns))
            ret->name = xmlNodeListGetString(doc, cur->childs, 1);
        if ((!strcmp(cur->name, "Email")) && (cur->ns == ns))
            ret->email = xmlNodeListGetString(doc, cur->childs, 1);
        cur = cur->next;
    }

    return(ret);
}

Here is a couple of things to notice:

  • Usually a recursive parsing style is the more convenient one, XML data being by nature subject to repetitive constructs and usualy exibit highly stuctured patterns.
  • The two arguments of type xmlDocPtr and xmlNsPtr, i.e. the pointer to the global XML document and the namespace reserved to the application. Document wide information are needed for example to decode entities and it's a good coding practice to define a namespace for your application set of data and test that the element and attributes you're analyzing actually pertains to your application space. This is done by a simple equality test (cur->ns == ns).
  • To retrieve text and attributes value, it is suggested to use the function xmlNodeListGetString to gather all the text and entity reference nodes generated by the DOM output and produce an single text string.

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

/*
 * 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->childs;
    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->childs, 1);
        if ((!strcmp(cur->name, "Category")) && (cur->ns == ns))
            ret->category = xmlNodeListGetString(doc, cur->childs, 1);
        if ((!strcmp(cur->name, "Contact")) && (cur->ns == ns))
            ret->contact = parsePerson(doc, ns, cur);
        cur = cur->next;
    }

    return(ret);
}

One can notice that once 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

Daniel Veillard

$Id: xml.html,v 1.28.2.1 2001/05/04 07:38:06 veillard Exp $