next up previous
Next: Design Issues Up: Reference to the Library Previous: Standard way to Create

A Simple Example

To illustrate some of the most common functionalities of Gdome2 we present here a simple example solving a frequent task, namely the removal of comments and blank nodes from a DOM tree. This can be useful, for example, to enforce some invariants on the position of nodes inside a validated document.
int main (int argc, char **argv)
  GdomeDOMImplementation *domimpl;
  GdomeDocument *domdoc;
  GdomeElement *rootel;
  GdomeException exc;

  domimpl = gdome_DOMImplementation_mkref();
  domdoc = gdome_DOMImplementation_parseFile (domimpl, argv[1], &exc);
  rootel = gdome_doc_documentElement (domdoc, &exc);

  cleanSubTree ((GdomeNode *)rootel);

  gdome_DOMImplementation_saveFile (domimpl, "out.xml", domdoc, &exc);

  gdome_DOMImplementation_freeDoc (domimpl, domdoc, &exc);
  gdome_DOMImplementation_unref (domimpl, &exc);

  return 0;
First of all, the Gdome2 user has to bootstrap the library and load the XML data file in a GdomeDocument object. Then, he recovers the reference to the root GdomeElement of the document by means of the gdome_doc_documentElement method. At that point, he invokes the cleaning function cleanSubTree and finally he saves the resulting document back to the file system. Let us now turn our attention to the cleaning function, described below:
void cleanSubTree (GdomeNode *node)
  GdomeNodeList *nl;
  GdomeException exc;
  GdomeNode *child;
  long i, nllength;

  nl = gdome_n_childNodes (node, &exc);
  if ((nllength = gdome_nl_length (nl, &exc)) == 0)

  for (i = nllength - 1 ; i >= 0; i--) {
    child = gdome_nl_item(nl, i, &exc);

    if (gdome_n_nodeType (child, &exc) == GDOME_COMMENT_NODE ||
        (gdome_n_nodeType (child, &exc) == GDOME_TEXT_NODE &&
         isSpaceStr (gdome_t_data ((GdomeText *)child, &exc))))
      gdome_n_removeChild (node, child, &exc);
    else if (gdome_n_hasChildNodes (child, &exc))
      cleanSubTree (child);
Indeed, the code is quite self-explanatory: we make a traversal of the interested sub-tree with a recursive visit on the important children found in the NodeList. Discardable children (comments and blank text nodes in the example) are removed as they are met.

Paolo Casarini 2001-04-01