xml.html revision 10a2c6532a409760cf46b70dba7b8d09617d75e3
1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
2                      "http://www.w3.org/TR/REC-html40/loose.dtd">
3<html>
4<head>
5  <title>The XML library for Gnome</title>
6  <meta name="GENERATOR" content="amaya V2.2">
7</head>
8
9<body bgcolor="#ffffff">
10<h1 align="center">The XML library for Gnome</h1>
11
12<h2 style="text-align: center">libxml, a.k.a. gnome-xml</h2>
13
14<p></p>
15<ul>
16  <li><a href="#Introducti">Introduction</a></li>
17  <li><a href="#Documentat">Documentation</a></li>
18  <li><a href="#Downloads">Downloads</a></li>
19  <li><a href="#News">News</a></li>
20  <li><a href="#XML">XML</a></li>
21  <li><a href="#tree">The tree output</a></li>
22  <li><a href="#interface">The SAX interface</a></li>
23  <li><a href="#library">The XML library interfaces</a>
24    <ul>
25      <li><a href="#Invoking">Invoking the parser</a></li>
26      <li><a href="#Building">Building a tree from scratch</a></li>
27      <li><a href="#Traversing">Traversing the tree</a></li>
28      <li><a href="#Modifying">Modifying the tree</a></li>
29      <li><a href="#Saving">Saving the tree</a></li>
30      <li><a href="#Compressio">Compression</a></li>
31    </ul>
32  </li>
33  <li><a href="#Entities">Entities or no entities</a></li>
34  <li><a href="#Namespaces">Namespaces</a></li>
35  <li><a href="#Validation">Validation</a></li>
36  <li><a href="#Principles">DOM principles</a></li>
37  <li><a href="#real">A real example</a></li>
38</ul>
39
40<h2><a name="Introducti">Introduction</a></h2>
41
42<p>This document describes the <a href="http://www.w3.org/XML/">XML</a>
43library provideed in the <a href="http://www.gnome.org/">Gnome</a> framework.
44XML is a standard to build tag based structured documents/data.</p>
45
46<p>The internal document repesentation is as close as possible to the <a
47href="http://www.w3.org/DOM/">DOM</a> interfaces.</p>
48
49<p>Libxml also has a <a href="http://www.megginson.com/SAX/index.html">SAX
50interface</a>, <a href="mailto:james@daa.com.au">James Henstridge</a> made <a
51href="http://www.daa.com.au/~james/gnome/xml-sax/xml-sax.html">a nice
52documentation</a> expaining how to use it. The interface is as compatible as
53possible with <a href="http://www.jclark.com/xml/expat.html">Expat</a>
54one.</p>
55
56<p>There is also a mailing-list <a
57href="mailto:xml@rufus.w3.org">xml@rufus.w3.org</a> for libxml, with an <a
58href="http://xmlsoft.org/messages">on-line archive</a>. To
59subscribe to this majordomo based list, send a mail to <a
60href="mailto:majordomo@rufus.w3.org">majordomo@rufus.w3.org</a> with
61"subscribe xml" in the <strong>content</strong> of the message.</p>
62
63<p>This library is released both under the W3C Copyright and the GNU LGP,
64basically everybody should be happy, if not, drop me a mail.</p>
65
66<p>People are invited to use the <a
67href="http://cvs.gnome.org/lxr/source/gdome/">gdome Gnome module to</a> get a
68full DOM interface, thanks to <a href="mailto:raph@levien.com">Raph
69Levien</a>, check his <a
70href="http://www.levien.com/gnome/domination.html">DOMination paper</a>. He
71uses it for his implementation of <a
72href="http://www.w3.org/Graphics/SVG/">SVG</a> called <a
73href="http://www.levien.com/svg/">gill</a>.</p>
74
75<h2><a name="Documentat">Documentation</a></h2>
76
77<p>The code is commented in a <a href=""></a>way which allow <a
78href="http://xmlsoft.org/libxml.html">extensive documentation</a>
79to be automatically extracted.</p>
80
81<p>At some point I will change the back-end to produce XML documentation in
82addition to SGML Docbook and HTML.</p>
83
84<h3>Reporting bugs</h3>
85
86<p>Well bugs or missing features are always possible, and I will make a point
87of fixing them in a timely fashion. The best way it to <a
88href="http://bugs.gnome.org/db/pa/lgnome-xml.html">use the Gnome bug tracking
89database</a>. I look at reports there regulary and it's good to have a
90reminder when a bug is still open. Check the <a
91href="http://bugs.gnome.org/Reporting.html">instructions on reporting bugs</a>
92and be sure to specify thatthe bug is for the package gnome-xml.</p>
93
94<p>Alternately you can just send the bug to the <a
95href="mailto:xml@rufus.w3.org">xml@rufus.w3.org</a> list.</p>
96
97<h2><a name="Downloads">Downloads</a></h2>
98
99<p>Latest version is 1.8.0, a bit experimental, stick with 1.7.4 if you
100experience trouble, you can find them on <a
101href="ftp://rpmfind.net/pub/veillard/">rpmfind.net</a> or on the <a
102href="ftp://ftp.gnome.org/pub/GNOME/MIRRORS.html">Gnome FTP server</a> either
103as a <a href="ftp://ftp.gnome.org/pub/GNOME/stable/sources/libxml/">source
104archive</a> or <a href="ftp://ftp.gnome.org/pub/GNOME/contrib/rpms/">RPMs
105packages</a>.</p>
106
107<p>Libxml is also available from 2 CVs bases:</p>
108<ul>
109  <li><p>The <a href="http://dev.w3.org/cvsweb/XML/">W3C CVS base</a>,
110    available read-only using the CVS pserver authentification:</p>
111    <pre>CVSROOT=:pserver:anonymous@dev.w3.org:/sources/public
112password: anonymous
113module: XML</pre>
114  </li>
115  <li><p>The <a
116    href="http://cvs.gnome.org/bonsai/rview.cgi?cvsroot=/cvs/gnome&dir=gnome-xml">Gnome
117    CVS base</a>, Check the <a
118    href="http://developer.gnome.org/tools/cvs.html">Gnome CVS Tools</a> page,
119    the CVS module is <b>gnome-xml</b></p>
120  </li>
121</ul>
122
123<h2><a name="News">News</a></h2>
124
125<h3>CVS only</h3>
126<ul>
127  <li>working on HTML and XML links recognition layers, get in touch with me
128    if you want to test those. </li>
129</ul>
130
131<h3>1.8.0: Dec 12 1999</h3>
132<ul>
133  <li>cleanup, especially memory wise</li>
134  <li>the parser should be more reliable, especially the HTML one, it should
135    not crash, whatever the input !</li>
136  <li>Integrated various patches, especially a speedup improvement for large
137    dataset from <a href="mailto:cnygard@bellatlantic.net">Carl Nygard</a>,
138    configure with --with-buffers to enable them.</li>
139  <li>attribute normalization, oops should have been added long ago !</li>
140  <li>attributes defaulted from Dtds should be available, xmlSetProp() now
141    does entities escapting by default.</li>
142</ul>
143
144<h3>1.7.4: Oct 25 1999</h3>
145<ul>
146  <li>Lots of HTML improvement</li>
147  <li>Fixed some errors when saving both XML and HTML</li>
148  <li>More examples, the regression tests should now look clean</li>
149  <li>Fixed a bug with contiguous charref</li>
150</ul>
151
152<h3>1.7.3: Sep 29 1999</h3>
153<ul>
154  <li>portability problems fixed</li>
155  <li>snprintf was used unconditionnally, leading to link problems on system
156    were it's not available, fixed</li>
157</ul>
158
159<h3>1.7.1: Sep 24 1999</h3>
160<ul>
161  <li>The basic type for strings manipulated by libxml has been renamed in
162    1.7.1 from <strong>CHAR</strong> to <strong>xmlChar</strong>. The reason
163    is that CHAR was conflicting with a predefined type on Windows. However on
164    non WIN32 environment, compatibility is provided by the way of  a
165    <strong>#define </strong>.</li>
166  <li>Changed another error : the use of a structure field called errno, and
167    leading to troubles on platforms where it's a macro</li>
168</ul>
169
170<h3>1.7.0: sep 23 1999</h3>
171<ul>
172  <li>Added the ability to fetch remote DTD or parsed entities, see the <a
173    href="gnome-xml-nanohttp.html">nanohttp</a> module.</li>
174  <li>Added an errno to report errors by another mean than a simple printf
175    like callback</li>
176  <li>Finished ID/IDREF support and checking when validation</li>
177  <li>Serious memory leaks fixed (there is now a <a
178    href="gnome-xml-xmlmemory.html">memory wrapper</a> module)</li>
179  <li>Improvement of <a href="http://www.w3.org/TR/xpath">XPath</a>
180    implementation</li>
181  <li>Added an HTML parser front-end</li>
182</ul>
183
184<h2><a name="XML">XML</a></h2>
185
186<p><a href="http://www.w3.org/TR/REC-xml">XML is a standard</a> for markup
187based structured documents, here is <a name="example">an example</a>:</p>
188<pre>&lt;?xml version="1.0"?>
189&lt;EXAMPLE prop1="gnome is great" prop2="&amp;amp; linux too">
190  &lt;head>
191   &lt;title>Welcome to Gnome&lt;/title>
192  &lt;/head>
193  &lt;chapter>
194   &lt;title>The Linux adventure&lt;/title>
195   &lt;p>bla bla bla ...&lt;/p>
196   &lt;image href="linus.gif"/>
197   &lt;p>...&lt;/p>
198  &lt;/chapter>
199&lt;/EXAMPLE></pre>
200
201<p>The first line specify that it's an XML document and gives useful
202informations about it's encoding. Then the document is a text format whose
203structure is specified by tags between brackets. <strong>Each tag opened have
204to be closed</strong> XML is pedantic about this, not that for example the
205image tag has no content (just an attribute) and is closed by ending up the
206tag with <code>/></code>.</p>
207
208<p>XML can be applied sucessfully to a wide range or usage from long term
209structured document maintenance where it follows the steps of SGML to simple
210data encoding mechanism like configuration file format (glade), spreadsheets
211(gnumeric), or even shorter lived document like in WebDAV where it is used to
212encode remote call between a client and a server.</p>
213
214<h2><a name="tree">The tree output</a></h2>
215
216<p>The parser returns a tree built during the document analysis. The value
217returned is an <strong>xmlDocPtr</strong> (i.e. a pointer to an
218<strong>xmlDoc</strong> structure). This structure contains informations like
219the file  name, the document type, and a <strong>root</strong> pointer which
220is the root of the document (or more exactly the first child under the root
221which is the document). The tree is made of <strong>xmlNode</strong>s, chained
222in double linked lists of siblings and with childs&lt;->parent relationship.
223An xmlNode can also carry properties (a chain of xmlAttr structures). An
224attribute may have a value which is a list of TEXT or ENTITY_REF nodes.</p>
225
226<p>Here is an example (erroneous w.r.t. the XML spec since there should be
227only one ELEMENT under the root):</p>
228
229<p><img src="structure.gif" alt=" structure.gif "></p>
230
231<p>In the source package there is a small program (not installed by default)
232called <strong>tester</strong> which parses XML files given as argument and
233prints them back as parsed, this is useful to detect errors both in XML code
234and in the XML parser itself. It has an option <strong>--debug</strong> which
235prints the actual in-memory structure of the document, here is the result with
236the <a href="#example">example</a> given before:</p>
237<pre>DOCUMENT
238version=1.0
239standalone=true
240  ELEMENT EXAMPLE
241    ATTRIBUTE prop1
242      TEXT
243      content=gnome is great
244    ATTRIBUTE prop2
245      ENTITY_REF
246      TEXT
247      content= too
248    ELEMENT head
249      ELEMENT title
250        TEXT
251        content=Welcome to Gnome
252    ELEMENT chapter
253      ELEMENT title
254        TEXT
255        content=The Linux adventure
256      ELEMENT p
257        TEXT
258        content=bla bla bla ...
259      ELEMENT image
260        ATTRIBUTE href
261          TEXT
262          content=linus.gif
263      ELEMENT p
264        TEXT
265        content=...</pre>
266
267<p>This should be useful to learn the internal representation model.</p>
268
269<h2><a name="interface">The SAX interface</a></h2>
270
271<p>Sometimes the DOM tree output is just to large to fit reasonably into
272memory. In that case and if you don't expect to save back the XML document
273loaded using libxml, it's better to use the SAX interface of libxml. SAX is a
274<strong>callback based interface</strong> to the parser. Before parsing, the
275application layer register a customized set of callbacks which will be called
276by the library as it progresses through the XML input.</p>
277
278<p>To get a more detailed step-by-step guidance on using the SAX interface of
279libxml, <a href="mailto:james@daa.com.au">James Henstridge</a> made <a
280href="http://www.daa.com.au/~james/gnome/xml-sax/xml-sax.html">a nice
281documentation.</a></p>
282
283<p>You can debug the SAX behaviour by using the <strong>testSAX</strong>
284program located in the gnome-xml module (it's usually not shipped in the
285binary packages of libxml, but you can also find it in the tar source
286distribution). Here is the sequence of callback that would be generated when
287parsing the example given before as reported by testSAX:</p>
288<pre>SAX.setDocumentLocator()
289SAX.startDocument()
290SAX.getEntity(amp)
291SAX.startElement(EXAMPLE, prop1='gnome is great', prop2='&amp;amp; linux too')
292SAX.characters(   , 3)
293SAX.startElement(head)
294SAX.characters(    , 4)
295SAX.startElement(title)
296SAX.characters(Welcome to Gnome, 16)
297SAX.endElement(title)
298SAX.characters(   , 3)
299SAX.endElement(head)
300SAX.characters(   , 3)
301SAX.startElement(chapter)
302SAX.characters(    , 4)
303SAX.startElement(title)
304SAX.characters(The Linux adventure, 19)
305SAX.endElement(title)
306SAX.characters(    , 4)
307SAX.startElement(p)
308SAX.characters(bla bla bla ..., 15)
309SAX.endElement(p)
310SAX.characters(    , 4)
311SAX.startElement(image, href='linus.gif')
312SAX.endElement(image)
313SAX.characters(    , 4)
314SAX.startElement(p)
315SAX.characters(..., 3)
316SAX.endElement(p)
317SAX.characters(   , 3)
318SAX.endElement(chapter)
319SAX.characters( , 1)
320SAX.endElement(EXAMPLE)
321SAX.endDocument()</pre>
322
323<p>Most of the other functionnalities of libxml are based on the DOM tree
324building facility, so nearly everything up to the end of this document
325presuppose the use of the standard DOM tree build. Note that the DOM tree
326itself is built by a set of registered default callbacks, without internal
327specific interface.</p>
328
329<h2><a name="library">The XML library interfaces</a></h2>
330
331<p>This section is directly intended to help programmers getting bootstrapped
332using the XML library from the C language. It doesn't intent to be extensive,
333I hope the automatically generated docs will provide the completeness
334required, but as a separated set of documents. The interfaces of the XML
335library are by principle low level, there is nearly zero abstration. Those
336interested in a higher level API should <a href="#DOM">look at DOM</a>.</p>
337
338<h3><a name="Invoking">Invoking the parser</a></h3>
339
340<p>Usually, the first thing to do is to read an XML input, the parser accepts
341to parse both memory mapped documents or direct files. The functions are
342defined in "parser.h":</p>
343<dl>
344  <dt><code>xmlDocPtr xmlParseMemory(char *buffer, int size);</code></dt>
345    <dd><p>parse a zero terminated string containing the document</p>
346    </dd>
347</dl>
348<dl>
349  <dt><code>xmlDocPtr xmlParseFile(const char *filename);</code></dt>
350    <dd><p>parse an XML document contained in a file (possibly compressed)</p>
351    </dd>
352</dl>
353
354<p>This returns a pointer to the document structure (or NULL in case of
355failure).</p>
356
357<p>A couple of comments can be made, first this mean that the parser is
358memory-hungry, first to load the document in memory, second to build the tree.
359Reading a document without building the tree will be possible in the future by
360pluggin the code to the SAX interface (see SAX.c).</p>
361
362<h3><a name="Building">Building a tree from scratch</a></h3>
363
364<p>The other way to get an XML tree in memory is by building it. Basically
365there is a set of functions dedicated to building new elements, those are also
366described in "tree.h", here is for example the piece of code producing the
367example used before:</p>
368<pre>    xmlDocPtr doc;
369    xmlNodePtr tree, subtree;
370
371    doc = xmlNewDoc("1.0");
372    doc->root = xmlNewDocNode(doc, NULL, "EXAMPLE", NULL);
373    xmlSetProp(doc->root, "prop1", "gnome is great");
374    xmlSetProp(doc->root, "prop2", "&amp;linux; too");
375    tree = xmlNewChild(doc->root, NULL, "head", NULL);
376    subtree = xmlNewChild(tree, NULL, "title", "Welcome to Gnome");
377    tree = xmlNewChild(doc->root, NULL, "chapter", NULL);
378    subtree = xmlNewChild(tree, NULL, "title", "The Linux adventure");
379    subtree = xmlNewChild(tree, NULL, "p", "bla bla bla ...");
380    subtree = xmlNewChild(tree, NULL, "image", NULL);
381    xmlSetProp(subtree, "href", "linus.gif");</pre>
382
383<p>Not really rocket science ...</p>
384
385<h3><a name="Traversing">Traversing the tree</a></h3>
386
387<p>Basically by including "tree.h" your code has access to the internal
388structure of all the element of the tree. The names should be somewhat simple
389like <strong>parent</strong>, <strong>childs</strong>, <strong>next</strong>,
390<strong>prev</strong>, <strong>properties</strong>, etc... For example still
391with the previous example:</p>
392<pre><code>doc->root->childs->childs</code></pre>
393
394<p>points to the title element,</p>
395<pre>doc->root->childs->next->child->child</pre>
396
397<p>points to the text node containing the chapter titlle "The Linux adventure"
398and</p>
399<pre>doc->root->properties->next->val</pre>
400
401<p>points to the entity reference containing the value of "&amp;linux" at the
402beginning of the second attribute of the root element "EXAMPLE".</p>
403
404<h3><a name="Modifying">Modifying the tree</a></h3>
405
406<p>functions are provided to read and write the document content:</p>
407<dl>
408  <dt><code>xmlAttrPtr xmlSetProp(xmlNodePtr node, const xmlChar *name, const
409  xmlChar *value);</code></dt>
410    <dd><p>This set (or change) an attribute carried by an ELEMENT node the
411      value can be NULL</p>
412    </dd>
413</dl>
414<dl>
415  <dt><code>const xmlChar *xmlGetProp(xmlNodePtr node, const xmlChar
416  *name);</code></dt>
417    <dd><p>This function returns a pointer to the property content, note that
418      no extra copy is made</p>
419    </dd>
420</dl>
421
422<p>Two functions must be used to read an write the text associated to
423elements:</p>
424<dl>
425  <dt><code>xmlNodePtr xmlStringGetNodeList(xmlDocPtr doc, const xmlChar
426  *value);</code></dt>
427    <dd><p>This function takes an "external" string and convert it to one text
428      node or possibly to a list of entity and text nodes. All non-predefined
429      entity references like &amp;Gnome; will be stored internally as an
430      entity node, hence the result of the function may not be a single
431      node.</p>
432    </dd>
433</dl>
434<dl>
435  <dt><code>xmlChar *xmlNodeListGetString(xmlDocPtr doc, xmlNodePtr list, int
436  inLine);</code></dt>
437    <dd><p>this is the dual function, which generate a new string containing
438      the content of the text and entity nodes. Note the extra argument
439      inLine, if set to 1 instead of returning the &amp;Gnome; XML encoding in
440      the string it will substitute it with it's value say "GNU Network Object
441      Model Environment". Set it if you want to use the string for non XML
442      usage like User Interface.</p>
443    </dd>
444</dl>
445
446<h3><a name="Saving">Saving a tree</a></h3>
447
448<p>Basically 3 options are possible:</p>
449<dl>
450  <dt><code>void xmlDocDumpMemory(xmlDocPtr cur, xmlChar**mem, int
451  *size);</code></dt>
452    <dd><p>returns a buffer where the document has been saved</p>
453    </dd>
454</dl>
455<dl>
456  <dt><code>extern void xmlDocDump(FILE *f, xmlDocPtr doc);</code></dt>
457    <dd><p>dumps a buffer to an open file descriptor</p>
458    </dd>
459</dl>
460<dl>
461  <dt><code>int xmlSaveFile(const char *filename, xmlDocPtr cur);</code></dt>
462    <dd><p>save the document ot a file. In that case the compression interface
463      is triggered if turned on</p>
464    </dd>
465</dl>
466
467<h3><a name="Compressio">Compression</a></h3>
468
469<p>The library handle transparently compression when doing file based
470accesses, the level of compression on saves can be tuned either globally or
471individually for one file:</p>
472<dl>
473  <dt><code>int  xmlGetDocCompressMode (xmlDocPtr doc);</code></dt>
474    <dd><p>Get the document compression ratio (0-9)</p>
475    </dd>
476</dl>
477<dl>
478  <dt><code>void xmlSetDocCompressMode (xmlDocPtr doc, int mode);</code></dt>
479    <dd><p>Set the document compression ratio</p>
480    </dd>
481</dl>
482<dl>
483  <dt><code>int  xmlGetCompressMode(void);</code></dt>
484    <dd><p>Get the default compression ratio</p>
485    </dd>
486</dl>
487<dl>
488  <dt><code>void xmlSetCompressMode(int mode);</code></dt>
489    <dd><p>set the default compression ratio</p>
490    </dd>
491</dl>
492
493<h2><a name="Entities">Entities or no entities</a></h2>
494
495<p>Entities principle is similar to simple C macros. They define an
496abbreviation for a given string that you can reuse many time through the
497content of your document. They are especially useful when frequent occurrences
498of a given string may occur within a document or to confine the change needed
499to a document to a restricted area in the internal subset of the document (at
500the beginning). Example:</p>
501<pre>1 &lt;?xml version="1.0"?>
5022 &lt;!DOCTYPE EXAMPLE SYSTEM "example.dtd" [
5033 &lt;!ENTITY xml "Extensible Markup Language">
5044 ]>
5055 &lt;EXAMPLE>
5066    &amp;xml;
5077 &lt;/EXAMPLE></pre>
508
509<p>Line 3 declares the xml entity. Line 6 uses the xml entity, by prefixing
510it's name with '&amp;' and following it by ';' without any spaces added. There
511are 5 predefined entities in libxml allowing to escape charaters with
512predefined meaning in some parts of the xml document content:
513<strong>&amp;lt;</strong> for the letter '&lt;', <strong>&amp;gt;</strong> for
514the letter '>',  <strong>&amp;apos;</strong> for the letter ''',
515<strong>&amp;quot;</strong> for the letter '"', and <strong>&amp;amp;</strong>
516for the letter '&amp;'.</p>
517
518<p>One of the problems related to entities is that you may want the parser to
519substitute entities content to see the replacement text in your application,
520or you may prefer keeping entities references as such in the content to be
521able to save the document back without loosing this usually precious
522information (if the user went through the pain of explicitley defining
523entities, he may have a a rather negative attitude if you blindly susbtitute
524them as saving time). The function <a
525href="gnome-xml-parser.html#XMLSUBSTITUTEENTITIESDEFAULT">xmlSubstituteEntitiesDefault()</a>
526allows to check and change the behaviour, which is to not substitute entities
527by default.</p>
528
529<p>Here is the DOM tree built by libxml for the previous document in the
530default case:</p>
531<pre>/gnome/src/gnome-xml -> /tester --debug test/ent1
532DOCUMENT
533version=1.0
534   ELEMENT EXAMPLE
535     TEXT
536     content=
537     ENTITY_REF
538       INTERNAL_GENERAL_ENTITY xml
539       content=Extensible Markup Language
540     TEXT
541     content=</pre>
542
543<p>And here is the result when substituting entities:</p>
544<pre>/gnome/src/gnome-xml -> /tester --debug --noent test/ent1
545DOCUMENT
546version=1.0
547   ELEMENT EXAMPLE
548     TEXT
549     content=     Extensible Markup Language</pre>
550
551<p>So entities or no entities ? Basically it depends on your use case, I
552suggest to keep the non-substituting default behaviour and avoid using
553entities in your XML document or data if you are not willing to handle the
554entity references elements in the DOM tree.</p>
555
556<p>Note that at save time libxml enforce the conversion of the predefined
557entities where necessary to prevent well-formedness problems, and will also
558transparently replace those with chars (i.e. will not generate entity
559reference elements in the DOM tree nor call the reference() SAX callback when
560finding them in the input).</p>
561
562<h2><a name="Namespaces">Namespaces</a></h2>
563
564<p>The libxml library implement namespace @@ support by recognizing namespace
565contructs in the input, and does namespace lookup automatically when building
566the DOM tree. A namespace declaration is associated with an in-memory
567structure and all elements or attributes within that namespace point to it.
568Hence testing the namespace is a simple and fast equality operation at the
569user level.</p>
570
571<p>I suggest it that people using libxml use a namespace, and declare it on
572the root element of their document as the default namespace. Then they dont
573need to happend the prefix in the content but we will have a basis for future
574semantic refinement and  merging of data from different sources. This doesn't
575augment significantly the size of the XML output, but significantly increase
576it's value in the long-term.</p>
577
578<p>Concerning the namespace value, this has to be an URL, but this doesn't
579have to point to any existing resource on the Web. I suggest using an URL
580within a domain you control, which makes sense and if possible holding some
581kind of versionning informations. For example
582<code>"http://www.gnome.org/gnumeric/1.0"</code> is a good namespace scheme.
583Then when you load a file, make sure that a namespace carrying the
584version-independant prefix is installed on the root element of your document,
585and if the version information don't match something you know, warn the user
586and be liberal in what you accept as the input. Also do *not* try to base
587namespace checking on the prefix value &lt;foo:text> may be exactly the same
588as &lt;bar:text>  in another document, what really matter is the URI
589associated with the element or the attribute, not the prefix string which is
590just a shortcut for the full URI.</p>
591
592<p>@@Interfaces@@</p>
593
594<p>@@Examples@@</p>
595
596<p>Usually people object using namespace in the case of validation, I object
597this and will make sure that using namespaces won't break validity checking,
598so even is you plan or are using validation I strongly suggest to add
599namespaces to your document. A default namespace scheme
600<code>xmlns="http://...."</code> should not break validity even on less
601flexible parsers. Now using namespace to mix and differenciate content coming
602from mutliple Dtd will certainly break current validation schemes, I will try
603to provide ways to do this, but this may not be portable or standardized.</p>
604
605<h2><a name="Validation">Validation, or are you afraid of DTDs ?</a></h2>
606
607<p>Well what is validation and what is a DTD ?</p>
608
609<p>Validation is the process of checking a document against a set of
610construction rules, a <strong>DTD</strong> (Document Type Definition) is such
611a set of rules.</p>
612
613<p>The validation process and building DTDs are the two most difficult parts
614of  XML life cycle. Briefly a DTD defines all the possibles element to be
615found within your document, what is the formal shape of your document tree (by
616defining the allowed content of an element, either text, a regular expression
617for the allowed list of children, or mixed content i.e. both text and childs).
618The DTD also defines the allowed attributes for all elements and the types of
619the attributes. For more detailed informations, I suggest to read the related
620parts of the XML specification, the examples found under
621gnome-xml/test/valid/dtd and the large amount of books available on XML. The
622dia example in gnome-xml/test/valid should be both simple and complete enough
623to allow you to build your own.</p>
624
625<p>A word of warning, building a good DTD which will fit your needs of your
626application in the long-term is far from trivial, however the extra level of
627quality it can insure is well worth the price for some sets of applications or
628if you already have already a DTD defined for your application field.</p>
629
630<p>The validation is not completely finished but in a (very IMHO) usable
631state. Until a real validation interface is defined the way to do it is to
632define and set the <strong>xmlDoValidityCheckingDefaultValue</strong> external
633variable to 1, this will of course be changed at some point:</p>
634
635<p>extern int xmlDoValidityCheckingDefaultValue;</p>
636
637<p>...</p>
638
639<p>xmlDoValidityCheckingDefaultValue = 1;</p>
640
641<p></p>
642
643<p>To handle external entities, use the function
644<strong>xmlSetExternalEntityLoader</strong>(xmlExternalEntityLoader f); to
645link in you HTTP/FTP/Entities database library to the standard libxml
646core.</p>
647
648<p>@@interfaces@@</p>
649
650<h2><a name="DOM"></a><a name="Principles">DOM Principles</a></h2>
651
652<p><a href="http://www.w3.org/DOM/">DOM</a> stands for the <em>Document Object
653Model</em> this is an API for accessing XML or HTML structured documents.
654Native support for DOM in Gnome is on the way (module gnome-dom), and it will
655be based on gnome-xml. This will be a far cleaner interface to manipulate XML
656files within Gnome since it won't expose the internal structure. DOM defines a
657set of IDL (or Java) interfaces allowing to traverse and manipulate a
658document. The DOM library will allow accessing and modifying "live" documents
659presents on other programs like this:</p>
660
661<p><img src="DOM.gif" alt=" DOM.gif "></p>
662
663<p>This should help greatly doing things like modifying a gnumeric spreadsheet
664embedded in a GWP document for example.</p>
665
666<p>The current DOM implementation on top of libxml is the <a
667href="http://cvs.gnome.org/lxr/source/gdome/">gdome Gnome module</a>, this is
668a full DOM interface, thanks to <a href="mailto:raph@levien.com">Raph
669Levien</a>.</p>
670
671<p>The gnome-dom module in the Gnome CVS base is obsolete</p>
672
673<h2><a name="Example"></a><a name="real">A real example</a></h2>
674
675<p>Here is a real size example, where the actual content of the application
676data is not kept in the DOM tree but uses internal structures. It is based on
677a proposal to keep a database of jobs related to Gnome, with an XML based
678storage structure. Here is an <a href="gjobs.xml">XML encoded jobs
679base</a>:</p>
680<pre>&lt;?xml version="1.0"?>
681&lt;gjob:Helping xmlns:gjob="http://www.gnome.org/some-location">
682  &lt;gjob:Jobs>
683
684    &lt;gjob:Job>
685      &lt;gjob:Project ID="3"/>
686      &lt;gjob:Application>GBackup&lt;/gjob:Application>
687      &lt;gjob:Category>Development&lt;/gjob:Category>
688
689      &lt;gjob:Update>
690        &lt;gjob:Status>Open&lt;/gjob:Status>
691        &lt;gjob:Modified>Mon, 07 Jun 1999 20:27:45 -0400 MET DST&lt;/gjob:Modified>
692        &lt;gjob:Salary>USD 0.00&lt;/gjob:Salary>
693      &lt;/gjob:Update>
694
695      &lt;gjob:Developers>
696        &lt;gjob:Developer>
697        &lt;/gjob:Developer>
698      &lt;/gjob:Developers>
699
700      &lt;gjob:Contact>
701        &lt;gjob:Person>Nathan Clemons&lt;/gjob:Person>
702        &lt;gjob:Email>nathan@windsofstorm.net&lt;/gjob:Email>
703        &lt;gjob:Company>
704        &lt;/gjob:Company>
705        &lt;gjob:Organisation>
706        &lt;/gjob:Organisation>
707        &lt;gjob:Webpage>
708        &lt;/gjob:Webpage>
709        &lt;gjob:Snailmail>
710        &lt;/gjob:Snailmail>
711        &lt;gjob:Phone>
712        &lt;/gjob:Phone>
713      &lt;/gjob:Contact>
714
715      &lt;gjob:Requirements>
716      The program should be released as free software, under the GPL.
717      &lt;/gjob:Requirements>
718
719      &lt;gjob:Skills>
720      &lt;/gjob:Skills>
721
722      &lt;gjob:Details>
723      A GNOME based system that will allow a superuser to configure 
724      compressed and uncompressed files and/or file systems to be backed 
725      up with a supported media in the system.  This should be able to 
726      perform via find commands generating a list of files that are passed 
727      to tar, dd, cpio, cp, gzip, etc., to be directed to the tape machine 
728      or via operations performed on the filesystem itself. Email 
729      notification and GUI status display very important.
730      &lt;/gjob:Details>
731
732    &lt;/gjob:Job>
733
734  &lt;/gjob:Jobs>
735&lt;/gjob:Helping></pre>
736
737<p>While loading the XML file into an internal DOM tree is a matter of calling
738only a couple of functions, browsing the tree to gather the informations and
739generate the internals structures is harder, and more error prone.</p>
740
741<p>The suggested principle is to be tolerant with respect to the input
742structure. For example the ordering of the attributes is not significant, Cthe
743XML specification is clear about it. It's also usually a good idea to not be
744dependant of the orders of the childs of a given node, unless it really makes
745things harder. Here is some code to parse the informations for a person:</p>
746<pre>/*
747 * A person record
748 */
749typedef struct person {
750    char *name;
751    char *email;
752    char *company;
753    char *organisation;
754    char *smail;
755    char *webPage;
756    char *phone;
757} person, *personPtr;
758
759/*
760 * And the code needed to parse it
761 */
762personPtr parsePerson(xmlDocPtr doc, xmlNsPtr ns, xmlNodePtr cur) {
763    personPtr ret = NULL;
764
765DEBUG("parsePerson\n");
766    /*
767     * allocate the struct
768     */
769    ret = (personPtr) malloc(sizeof(person));
770    if (ret == NULL) {
771        fprintf(stderr,"out of memory\n");
772        return(NULL);
773    }
774    memset(ret, 0, sizeof(person));
775
776    /* We don't care what the top level element name is */
777    cur = cur->childs;
778    while (cur != NULL) {
779        if ((!strcmp(cur->name, "Person")) &amp;&amp; (cur->ns == ns))
780            ret->name = xmlNodeListGetString(doc, cur->childs, 1);
781        if ((!strcmp(cur->name, "Email")) &amp;&amp; (cur->ns == ns))
782            ret->email = xmlNodeListGetString(doc, cur->childs, 1);
783        cur = cur->next;
784    }
785
786    return(ret);
787}</pre>
788
789<p>Here is a couple of things to notice:</p>
790<ul>
791  <li>Usually a recursive parsing style is the more convenient one, XML data
792    being by nature subject to repetitive constructs and usualy exibit highly
793    stuctured patterns.</li>
794  <li>The two arguments of type <em>xmlDocPtr</em> and <em>xmlNsPtr</em>, i.e.
795    the pointer to the global XML document and the namespace reserved to the
796    application. Document wide information are needed for example to decode
797    entities and it's a good coding practice to define a namespace for your
798    application set of data and test that the element and attributes you're
799    analyzing actually pertains to your application space. This is done by a
800    simple equality test (cur->ns == ns).</li>
801  <li>To retrieve text and attributes value, it is suggested to use the
802    function <em>xmlNodeListGetString</em> to gather all the text and entity
803    reference nodes generated by the DOM output and produce an single text
804    string.</li>
805</ul>
806
807<p>Here is another piece of code used to parse another level of the
808structure:</p>
809<pre>/*
810 * a Description for a Job
811 */
812typedef struct job {
813    char *projectID;
814    char *application;
815    char *category;
816    personPtr contact;
817    int nbDevelopers;
818    personPtr developers[100]; /* using dynamic alloc is left as an exercise */
819} job, *jobPtr;
820
821/*
822 * And the code needed to parse it
823 */
824jobPtr parseJob(xmlDocPtr doc, xmlNsPtr ns, xmlNodePtr cur) {
825    jobPtr ret = NULL;
826
827DEBUG("parseJob\n");
828    /*
829     * allocate the struct
830     */
831    ret = (jobPtr) malloc(sizeof(job));
832    if (ret == NULL) {
833        fprintf(stderr,"out of memory\n");
834        return(NULL);
835    }
836    memset(ret, 0, sizeof(job));
837
838    /* We don't care what the top level element name is */
839    cur = cur->childs;
840    while (cur != NULL) {
841        
842        if ((!strcmp(cur->name, "Project")) &amp;&amp; (cur->ns == ns)) {
843            ret->projectID = xmlGetProp(cur, "ID");
844            if (ret->projectID == NULL) {
845                fprintf(stderr, "Project has no ID\n");
846            }
847        }
848        if ((!strcmp(cur->name, "Application")) &amp;&amp; (cur->ns == ns))
849            ret->application = xmlNodeListGetString(doc, cur->childs, 1);
850        if ((!strcmp(cur->name, "Category")) &amp;&amp; (cur->ns == ns))
851            ret->category = xmlNodeListGetString(doc, cur->childs, 1);
852        if ((!strcmp(cur->name, "Contact")) &amp;&amp; (cur->ns == ns))
853            ret->contact = parsePerson(doc, ns, cur);
854        cur = cur->next;
855    }
856
857    return(ret);
858}</pre>
859
860<p>One can notice that once used to it, writing this kind of code is quite
861simple, but boring. Ultimately, it could be possble to write stubbers taking
862either C data structure definitions, a set of XML examples or an XML DTD and
863produce the code needed to import and export the content between C data and
864XML storage. This is left as an exercise to the reader :-)</p>
865
866<p>Feel free to use <a href="gjobread.c">the code for the full C parsing
867example</a> as a template, it is also available with Makefile in the Gnome CVS
868base under gnome-xml/example</p>
869
870<p></p>
871
872<p><a href="mailto:Daniel.Veillard@w3.org">Daniel Veillard</a></p>
873
874<p>$Id: xml.html,v 1.12 1999/11/19 17:46:26 veillard Exp $</p>
875</body>
876</html>
877