Separate documents:
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
There are some on-line resources about using libxml:
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.
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::
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
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:
The Gnome CVS base. Check the Gnome CVS Tools page; the CVS module is gnome-xml.
Items floating around but not actively worked on, get in touch with me if you want to test those
Lots of bugfixes, and added a basic SGML catalog support:
#include <libxml/xxx.h>
instead of
#include "xxx.h"
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="& 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.
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
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:
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):
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.
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='& 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.
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:
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).
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".
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()
.
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 ...
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.
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").
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.
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 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: < for the character '<', > for the character '>', ' for the character ''', " for the character '"', and & 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.
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.
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 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.
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
Website: http://lusis.org/~ari/xml++/
$Id: xml.html,v 1.108 2001/08/24 00:49:01 veillard Exp $