Contents Previous Next

Load Callbacks

Chapter 2 introduced the mxmlLoadFile() and mxmlLoadString() functions. The last argument to these functions is a callback function which is used to determine the value type of each data node in an XML document.

Mini-XML defines several standard callbacks for simple XML data files:

You can provide your own callback functions for more complex XML documents. Your callback function will receive a pointer to the current element node and must return the value type of the immediate children for that element node: MXML_INTEGER, MXML_OPAQUE, MXML_REAL, or MXML_TEXT. The function is called after the element and its attributes have been read, so you can look at the element name, attributes, and attribute values to determine the proper value type to return.

The following callback function looks for an attribute named "type" or the element name to determine the value type for its child nodes:

    /*
     * 'type_cb()' - XML data type callback for mxmlLoadFile()...
     */

    mxml_type_t                             /* O - Data type */
    type_cb(mxml_node_t *node)              /* I - Element node */
    {
      const char    *type;                  /* Type string */


     /*
      * You can lookup attributes and/or use the element name, hierarchy, etc...
      */

      if ((type = mxmlElementGetAttr(node, "type")) == NULL)
	type = node->value.element.name;

      if (!strcmp(type, "integer"))
	return (MXML_INTEGER);
      else if (!strcmp(type, "opaque"))
	return (MXML_OPAQUE);
      else if (!strcmp(type, "real"))
	return (MXML_REAL);
      else
	return (MXML_TEXT);
    }

To use this callback function, simply use the name when you call any of the load functions:

    FILE *fp;
    mxml_node_t *tree;

    fp = fopen("filename.xml", "r");
    tree = mxmlLoadFile(NULL, fp, type_cb);
    fclose(fp);

Contents Previous Next