Contents Previous Next

Loading and Saving XML Files

You load an XML file using the mxmlLoadFile() function:

    FILE *fp;
    mxml_node_t *tree;

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

The third argument specifies a callback function which returns the value type of the immediate children for a new element node: MXML_INTEGER, MXML_OPAQUE, MXML_REAL, or MXML_TEXT. This 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 default value type is MXML_TEXT if no callback is used.

Similarly, you save an XML file using the mxmlSaveFile() function:

    FILE *fp;
    mxml_node_t *tree;

    fp = fopen("filename.xml", "w");
    mxmlSaveFile(tree, fp, MXML_NO_CALLBACK);
    fclose(fp);

Callback functions for saving are used to optionally insert whitespace before and after elements in the node tree. Your function will be called up to four times for each element node with a pointer to the node and a "where" value of MXML_WS_BEFORE_OPEN, MXML_WS_AFTER_OPEN, MXML_WS_BEFORE_CLOSE, or MXML_WS_AFTER_CLOSE. The callback function should return NULL if no whitespace should be added and the string to insert (spaces, tabs, carriage returns, and newlines) otherwise.

The mxmlLoadString() , mxmlSaveAllocString() , and mxmlSaveString() functions load XML node trees from and save XML node trees to strings:

    char buffer[8192];
    char *ptr;
    mxml_node_t *tree;

    ...
    tree = mxmlLoadString(NULL, buffer, MXML_NO_CALLBACK);

    ...
    mxmlSaveString(tree, buffer, sizeof(buffer), MXML_NO_CALLBACK);

    ...
    ptr = mxmlSaveAllocString(tree, MXML_NO_CALLBACK);

Contents Previous Next