blob: a5afae11266e336611edb43302f54057a249865d [file] [log] [blame]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>The XML library for Gnome</title>
<meta name="GENERATOR" content="amaya V2.1">
</head>
<body bgcolor="#ffffff">
<h1 align="center">The XML library for Gnome</h1>
<h2 style="text-align: center">libxml, a.k.a. gnome-xml</h2>
<p></p>
<p>This document describes the <a href="http://www.w3.org/XML/">XML</a>
library provideed in the <a href="http://www.gnome.org/">Gnome</a> framework.
XML is a standard to build tag based structured documents/data.</p>
<p>The internal document repesentation is as close as possible to the <a
href="http://www.w3.org/DOM/">DOM</a> interfaces.</p>
<p>Libxml also has a <a href="http://www.megginson.com/SAX/index.html">SAX
interface</a>, <a href="mailto:james@daa.com.au">James Henstridge</a> made <a
href="http://www.daa.com.au/~james/gnome/xml-sax/xml-sax.html">a nice
documentation</a> expaining how to use it. The interface is as compatible as
possible with <a href="http://www.jclark.com/xml/expat.html">Expat</a>
one.</p>
<p>There is also a mailing-list <a
href="mailto:xml@rufus.w3.org">xml@rufus.w3.org</a> for libxml, with an <a
href="http://rpmfind.net/veillard/XML/messages">on-line archive</a>. To
subscribe to this majordomo based list, send a mail to <a
href="mailto:majordomo@rufus.w3.org">majordomo@rufus.w3.org</a> with
"subscribe xml" in the <strong>content</strong> of the message.</p>
<p>This library is released both under the W3C Copyright and the GNU LGP,
basically everybody should be happy, if not, drop me a mail.</p>
<p>People are invited to use the <a
href="http://cvs.gnome.org/lxr/source/gdome/">gdome Gnome module to</a> get a
full DOM interface, thanks to <a href="mailto:raph@levien.com">Raph
Levien</a>, check his <a
href="http://www.levien.com/gnome/domination.html">DOMination paper</a>. He
uses it for his implementation of <a
href="http://www.w3.org/Graphics/SVG/">SVG</a> called <a
href="http://www.levien.com/svg/">gill</a>.</p>
<h2>Extensive documentation</h2>
<p>The code is commented in a <a href=""></a>way which allow <a
href="http://rpmfind.net/veillard/XML/libxml.html">extensive documentation</a>
to be automatically extracted.</p>
<p>At some point I will change the back-end to produce XML documentation in
addition to SGML Docbook and HTML.</p>
<h2>XML</h2>
<p><a href="http://www.w3.org/TR/REC-xml">XML is a standard</a> for markup
based structured documents, here is <a name="example">an example</a>:</p>
<pre>&lt;?xml version="1.0"?>
&lt;EXAMPLE prop1="gnome is great" prop2="&amp;amp; linux too">
&lt;head>
&lt;title>Welcome to Gnome&lt;/title>
&lt;/head>
&lt;chapter>
&lt;title>The Linux adventure&lt;/title>
&lt;p>bla bla bla ...&lt;/p>
&lt;image href="linus.gif"/>
&lt;p>...&lt;/p>
&lt;/chapter>
&lt;/EXAMPLE></pre>
<p>The first line specify that it's an XML document and gives useful
informations about it's encoding. Then the document is a text format whose
structure is specified by tags between brackets. <strong>Each tag opened have
to be closed</strong> XML is pedantic about this, not that for example the
image tag has no content (just an attribute) and is closed by ending up the
tag with <code>/></code>.</p>
<p>XML can be applied sucessfully to a wide range or usage from long term
structured document maintenance where it follows the steps of SGML to simple
data encoding mechanism like configuration file format (glade), spreadsheets
(gnumeric), or even shorter lived document like in WebDAV where it is used to
encode remote call between a client and a server.</p>
<h2>The tree output</h2>
<p>The parser returns a tree built during the document analysis. The value
returned is an <strong>xmlDocPtr</strong> (i.e. a pointer to an
<strong>xmlDoc</strong> structure). This structure contains informations like
the file name, the document type, and a <strong>root</strong> 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 <strong>xmlNode</strong>s, chained
in double linked lists of siblings and with childs&lt;->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.</p>
<p>Here is an example (erroneous w.r.t. the XML spec since there should be
only one ELEMENT under the root):</p>
<p><img src="structure.gif" alt=" structure.gif "></p>
<p>In the source package there is a small program (not installed by default)
called <strong>tester</strong> which parses XML files given as argument and
prints them back as parsed, this is useful to detect errors both in XML code
and in the XML parser itself. It has an option <strong>--debug</strong> which
prints the actual in-memory structure of the document, here is the result with
the <a href="#example">example</a> given before:</p>
<pre>DOCUMENT
version=1.0
standalone=true
ELEMENT EXAMPLE
ATTRIBUTE prop1
TEXT
content=gnome is great
ATTRIBUTE prop2
ENTITY_REF
TEXT
content= 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=...</pre>
<p>This should be useful to learn the internal representation model.</p>
<h2>The SAX interface</h2>
<p>Sometimes the DOM tree output is just to 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
<strong>callback based interface</strong> to the parser. Before parsing, the
application layer register a customized set of callbacks which will be called
by the library as it progresses through the XML input.</p>
<p>To get a more detailed step-by-step guidance on using the SAX interface of
libxml, <a href="mailto:james@daa.com.au">James Henstridge</a> made <a
href="http://www.daa.com.au/~james/gnome/xml-sax/xml-sax.html">a nice
documentation.</a></p>
<p>You can debug the SAX behaviour by using the <strong>testSAX</strong>
program located in the gnome-xml module (it's usually not shipped in the
binary packages of libxml, but you can also find it in the tar source
distribution). Here is the sequence of callback that would be generated when
parsing the example given before as reported by testSAX:</p>
<pre>SAX.setDocumentLocator()
SAX.startDocument()
SAX.getEntity(amp)
SAX.startElement(EXAMPLE, prop1='gnome is great', prop2='&amp;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()</pre>
<p>Most of the other functionnalities of libxml are based on the DOM tree
building facility, so nearly everything up to the end of this document
presuppose 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.</p>
<h2>The XML library interfaces</h2>
<p>This section is directly intended to help programmers getting bootstrapped
using the XML library from the C language. It doesn't intent to be extensive,
I hope the automatically generated docs will provide the completeness
required, but as a separated set of documents. The interfaces of the XML
library are by principle low level, there is nearly zero abstration. Those
interested in a higher level API should <a href="#DOM">look at DOM</a>.</p>
<h3>Invoking the parser</h3>
<p>Usually, the first thing to do is to read an XML input, the parser accepts
to parse both memory mapped documents or direct files. The functions are
defined in "parser.h":</p>
<dl>
<dt><code>xmlDocPtr xmlParseMemory(char *buffer, int size);</code></dt>
<dd><p>parse a zero terminated string containing the document</p>
</dd>
</dl>
<dl>
<dt><code>xmlDocPtr xmlParseFile(const char *filename);</code></dt>
<dd><p>parse an XML document contained in a file (possibly compressed)</p>
</dd>
</dl>
<p>This returns a pointer to the document structure (or NULL in case of
failure).</p>
<p>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 will be possible in the future by
pluggin the code to the SAX interface (see SAX.c).</p>
<h3>Building a tree from scratch</h3>
<p>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, those are also
described in "tree.h", here is for example the piece of code producing the
example used before:</p>
<pre> 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", "&amp;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");</pre>
<p>Not really rocket science ...</p>
<h3>Traversing the tree</h3>
<p>Basically by including "tree.h" your code has access to the internal
structure of all the element of the tree. The names should be somewhat simple
like <strong>parent</strong>, <strong>childs</strong>, <strong>next</strong>,
<strong>prev</strong>, <strong>properties</strong>, etc... For example still
with the previous example:</p>
<pre><code>doc->root->childs->childs</code></pre>
<p>points to the title element,</p>
<pre>doc->root->childs->next->child->child</pre>
<p>points to the text node containing the chapter titlle "The Linux adventure"
and</p>
<pre>doc->root->properties->next->val</pre>
<p>points to the entity reference containing the value of "&amp;linux" at the
beginning of the second attribute of the root element "EXAMPLE".</p>
<h3>Modifying the tree</h3>
<p>functions are provided to read and write the document content:</p>
<dl>
<dt><code>xmlAttrPtr xmlSetProp(xmlNodePtr node, const CHAR *name, const
CHAR *value);</code></dt>
<dd><p>This set (or change) an attribute carried by an ELEMENT node the
value can be NULL</p>
</dd>
</dl>
<dl>
<dt><code>const CHAR *xmlGetProp(xmlNodePtr node, const CHAR
*name);</code></dt>
<dd><p>This function returns a pointer to the property content, note that
no extra copy is made</p>
</dd>
</dl>
<p>Two functions must be used to read an write the text associated to
elements:</p>
<dl>
<dt><code>xmlNodePtr xmlStringGetNodeList(xmlDocPtr doc, const CHAR
*value);</code></dt>
<dd><p>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 &amp;Gnome; will be stored internally as an
entity node, hence the result of the function may not be a single
node.</p>
</dd>
</dl>
<dl>
<dt><code>CHAR *xmlNodeListGetString(xmlDocPtr doc, xmlNodePtr list, int
inLine);</code></dt>
<dd><p>this is the dual function, which generate a new string containing
the content of the text and entity nodes. Note the extra argument
inLine, if set to 1 instead of returning the &amp;Gnome; XML encoding in
the string it will substitute it with it's value say "GNU Network Object
Model Environment". Set it if you want to use the string for non XML
usage like User Interface.</p>
</dd>
</dl>
<h3>Saving a tree</h3>
<p>Basically 3 options are possible:</p>
<dl>
<dt><code>void xmlDocDumpMemory(xmlDocPtr cur, CHAR**mem, int
*size);</code></dt>
<dd><p>returns a buffer where the document has been saved</p>
</dd>
</dl>
<dl>
<dt><code>extern void xmlDocDump(FILE *f, xmlDocPtr doc);</code></dt>
<dd><p>dumps a buffer to an open file descriptor</p>
</dd>
</dl>
<dl>
<dt><code>int xmlSaveFile(const char *filename, xmlDocPtr cur);</code></dt>
<dd><p>save the document ot a file. In that case the compression interface
is triggered if turned on</p>
</dd>
</dl>
<h3>Compression</h3>
<p>The library handle transparently compression when doing file based
accesses, the level of compression on saves can be tuned either globally or
individually for one file:</p>
<dl>
<dt><code>int xmlGetDocCompressMode (xmlDocPtr doc);</code></dt>
<dd><p>Get the document compression ratio (0-9)</p>
</dd>
</dl>
<dl>
<dt><code>void xmlSetDocCompressMode (xmlDocPtr doc, int mode);</code></dt>
<dd><p>Set the document compression ratio</p>
</dd>
</dl>
<dl>
<dt><code>int xmlGetCompressMode(void);</code></dt>
<dd><p>Get the default compression ratio</p>
</dd>
</dl>
<dl>
<dt><code>void xmlSetCompressMode(int mode);</code></dt>
<dd><p>set the default compression ratio</p>
</dd>
</dl>
<h2>Entities or no entities</h2>
<p>Entities principle is similar to simple C macros. They define an
abbreviation for a given string that you can reuse many time through the
content of your document. They are especially useful when frequent occurrences
of a given string may occur 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:</p>
<pre>1 &lt;?xml version="1.0"?>
2 &lt;!DOCTYPE EXAMPLE SYSTEM "example.dtd" [
3 &lt;!ENTITY xml "Extensible Markup Language">
4 ]>
5 &lt;EXAMPLE>
6 &amp;xml;
7 &lt;/EXAMPLE>
</pre>
<p>Line 3 declares the xml entity. Line 6 uses the xml entity, by prefixing
it's name with '&amp;' and following it by ';' without any spaces added.
There are 5 predefined entities in libxml allowing to escape charaters with
predefined meaning in some parts of the xml document content:
<strong>&amp;lt;</strong> for the letter '&lt;', <strong>&amp;gt;</strong> for
the letter '>', <strong>&amp;apos;</strong> for the letter ''',
<strong>&amp;quot;</strong> for the letter '"', and
<strong>&amp;amp;</strong> for the letter '&amp;'.</p>
<p>One of the problems related to entities is that you may want the parser to
substitute entities content to see the replacement text in your application,
or you may prefer keeping entities references as such in the content to be
able to save the document back without loosing this usually precious
information (if the user went through the pain of explicitley defining
entities, he may have a a rather negative attitude if you blindly susbtitute
them as saving time). The function <a
href="gnome-xml-parser.html#XMLSUBSTITUTEENTITIESDEFAULT">xmlSubstituteEntitiesDefault()</a>
allows to check and change the behaviour, which is to not substitute entities
by default.</p>
<p>Here is the DOM tree built by libxml for the previous document in the
default case:</p>
<pre>/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=</pre>
<p>And here is the result when substituting entities:</p>
<pre>/gnome/src/gnome-xml -> ./tester --debug --noent test/ent1
DOCUMENT
version=1.0
ELEMENT EXAMPLE
TEXT
content= Extensible Markup Language</pre>
<p>So entities or no entities ? Basically it depends on your use case, I
suggest to 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.</p>
<p>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. will not generate entity
reference elements in the DOM tree nor call the reference() SAX callback when
finding them in the input).</p>
<h2>Namespaces</h2>
<p>The libxml library implement 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. </p>
<p>I suggest it that people using libxml use a namespace, and declare it on
the root element of their document as the default namespace. Then they dont
need to happend 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
it's value in the long-term.</p>
<p>Concerning the namespace value, this has to be an URL, but this doesn't
have to point to any existing resource on the Web. I suggest using an URL
within a domain you control, which makes sense and if possible holding some
kind of versionning informations. For example
<code>"http://www.gnome.org/gnumeric/1.0"</code> is a good namespace scheme.
Then when you load a file, make sure that a namespace carrying the
version-independant 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 &lt;foo:text> may be exactly the same
as &lt;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.</p>
<p>@@Interfaces@@</p>
<p>@@Examples@@</p>
<p>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 or are using validation I strongly suggest to add
namespaces to your document. A default namespace scheme
<code>xmlns="http://...."</code> should not break validity even on less
flexible parsers. Now using namespace to mix and differenciate content coming
from mutliple Dtd will certainly break current validation schemes, I will try
to provide ways to do this, but this may not be portable or standardized.</p>
<h2>Validation, or are you afraid of DTDs ?</h2>
<p>Well what is validation and what is a DTD ?</p>
<p>Validation is the process of checking a document against a set of
construction rules, a <strong>DTD</strong> (Document Type Definition) is such
a set of rules.</p>
<p>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.</p>
<p>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.</p>
<p>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 <strong>xmlDoValidityCheckingDefaultValue</strong> external
variable to 1, this will of course be changed at some point:</p>
<p>extern int xmlDoValidityCheckingDefaultValue;</p>
<p>...</p>
<p>xmlDoValidityCheckingDefaultValue = 1;</p>
<p></p>
<p>To handle external entities, use the function
<strong>xmlSetExternalEntityLoader</strong>(xmlExternalEntityLoader f); to
link in you HTTP/FTP/Entities database library to the standard libxml
core.</p>
<p>@@interfaces@@</p>
<h2><a name="DOM">DOM Principles</a></h2>
<p><a href="http://www.w3.org/DOM/">DOM</a> stands for the <em>Document Object
Model</em> 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:</p>
<p><img src="DOM.gif" alt=" DOM.gif "></p>
<p>This should help greatly doing things like modifying a gnumeric spreadsheet
embedded in a GWP document for example.</p>
<p>The current DOM implementation on top of libxml is the <a
href="http://cvs.gnome.org/lxr/source/gdome/">gdome Gnome module</a>, this is
a full DOM interface, thanks to <a href="mailto:raph@levien.com">Raph
Levien</a>.</p>
<p>The gnome-dom module in the Gnome CVS base is obsolete</p>
<h2><a name="Example">A real example</a></h2>
<p>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 <a href="gjobs.xml">XML encoded jobs
base</a>:</p>
<pre>&lt;?xml version="1.0"?>
&lt;gjob:Helping xmlns:gjob="http://www.gnome.org/some-location">
&lt;gjob:Jobs>
&lt;gjob:Job>
&lt;gjob:Project ID="3"/>
&lt;gjob:Application>GBackup&lt;/gjob:Application>
&lt;gjob:Category>Development&lt;/gjob:Category>
&lt;gjob:Update>
&lt;gjob:Status>Open&lt;/gjob:Status>
&lt;gjob:Modified>Mon, 07 Jun 1999 20:27:45 -0400 MET DST&lt;/gjob:Modified>
&lt;gjob:Salary>USD 0.00&lt;/gjob:Salary>
&lt;/gjob:Update>
&lt;gjob:Developers>
&lt;gjob:Developer>
&lt;/gjob:Developer>
&lt;/gjob:Developers>
&lt;gjob:Contact>
&lt;gjob:Person>Nathan Clemons&lt;/gjob:Person>
&lt;gjob:Email>nathan@windsofstorm.net&lt;/gjob:Email>
&lt;gjob:Company>
&lt;/gjob:Company>
&lt;gjob:Organisation>
&lt;/gjob:Organisation>
&lt;gjob:Webpage>
&lt;/gjob:Webpage>
&lt;gjob:Snailmail>
&lt;/gjob:Snailmail>
&lt;gjob:Phone>
&lt;/gjob:Phone>
&lt;/gjob:Contact>
&lt;gjob:Requirements>
The program should be released as free software, under the GPL.
&lt;/gjob:Requirements>
&lt;gjob:Skills>
&lt;/gjob:Skills>
&lt;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.
&lt;/gjob:Details>
&lt;/gjob:Job>
&lt;/gjob:Jobs>
&lt;/gjob:Helping></pre>
<p>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.</p>
<p>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
dependant 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:</p>
<pre>/*
* 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")) &amp;&amp; (cur->ns == ns))
ret->name = xmlNodeListGetString(doc, cur->childs, 1);
if ((!strcmp(cur->name, "Email")) &amp;&amp; (cur->ns == ns))
ret->email = xmlNodeListGetString(doc, cur->childs, 1);
cur = cur->next;
}
return(ret);
}</pre>
<p>Here is a couple of things to notice:</p>
<ul>
<li>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.</li>
<li>The two arguments of type <em>xmlDocPtr</em> and <em>xmlNsPtr</em>, 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).</li>
<li>To retrieve text and attributes value, it is suggested to use the
function <em>xmlNodeListGetString</em> to gather all the text and entity
reference nodes generated by the DOM output and produce an single text
string.</li>
</ul>
<p>Here is another piece of code used to parse another level of the
structure:</p>
<pre>/*
* 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")) &amp;&amp; (cur->ns == ns)) {
ret->projectID = xmlGetProp(cur, "ID");
if (ret->projectID == NULL) {
fprintf(stderr, "Project has no ID\n");
}
}
if ((!strcmp(cur->name, "Application")) &amp;&amp; (cur->ns == ns))
ret->application = xmlNodeListGetString(doc, cur->childs, 1);
if ((!strcmp(cur->name, "Category")) &amp;&amp; (cur->ns == ns))
ret->category = xmlNodeListGetString(doc, cur->childs, 1);
if ((!strcmp(cur->name, "Contact")) &amp;&amp; (cur->ns == ns))
ret->contact = parsePerson(doc, ns, cur);
cur = cur->next;
}
return(ret);
}</pre>
<p>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 :-)</p>
<p>Feel free to use <a href="gjobread.c">the code for the full C parsing
example</a> as a template, it is also available with Makefile in the Gnome CVS
base under gnome-xml/example</p>
<p></p>
<p><a href="mailto:Daniel.Veillard@w3.org">Daniel Veillard</a></p>
<p>$Id: xml.html,v 1.7 1999/09/04 18:27:23 veillard Exp $</p>
</body>
</html>