Coding Philosophy

Data structures

How to

Handling Unicode

Download sxmlc files

Project detail and discuss

Get support

How to

Handle XML documents

An XML document is described by the XMLDoc struct and is handled through all XMLDoc_* methods.
All calls to these methods are supposed made on an already-initialized document:
Create and initialize an XMLDoc object:

XMLDoc doc;
XMLDoc* doc = (XMLDoc*)malloc(sizeof(XMLDoc));

Read an XML document from a file

It is as simple as a call to one of the XMLDoc_parse_file method:

XMLDoc_parse_file("path_to_my_file.xml", &doc);
XMLDoc_parse_file_DOM("path_to_my_file.xml", &doc);
XMLDoc_parse_file_SAX("path_to_my_file.xml", &sax_callbacks, &user_data);
The first two methods are the same and use the DOM implementation, creating the XML tree internally. You can navigate through it after the whole file has been loaded (to add or remove nodes).
The last method uses SAX implementation and calls the callback functions given in sax_callbacks.

SAX parser

The SAX parser is called with an extra user_data argument that will be given back to all callbacks. It can be a pointer to an XMLDoc structure or any other user-defined info.
There are only 6 callbacks that can be called when using the SAX parser (plus an additional one if needed):

  • start_doc is called when document parsing starts, before parsing the first node.
  • start_node is called when a new node has been found (e.g. "<newNode param="val">")
  • end_node is called when a node is being closed. (e.g. "</newNode>")
  • new_text is called when text has been read from a node(e.g. "<newNode>My text</newNode>")
  • end_doc is called when document parsing ends. No other callbacks will be called after.
  • on_error is called when an error occurs during parsing. Parsing stops after.
  • all_event is given for those who prefer to handle all such events in a single function instead of three (e.g. to get a static variable for the node)
Each callback receive a SAX_Data argument where it is possible to know the name of the file/stream being parsed and the line number in the stream. This also where the user_data is found back.

Both start_node and end_node receive an XMLNode parameter which contains information about the tag and all attributes read.
It also has the tag_type attribute set to know if the node is a comment or prolog.

Each callback should return non-zero to tell the parser to go on with parsing, or return 0 to stop parsing.
NB: it is possible to change the callbacks by passing the 'sax_callbacks' as the 'user_data' as well, and changing it inside the callback itself!

int end(const XMLNode* node, SAX_Callbacks* cb);
int my_special_end(const XMLNode* node, SAX_Callbacks* cb);

int end(const XMLNode* node, SAX_Callbacks* cb)
	/* Process end of 'node' */

int start(const XMLNode* node, SAX_Callbacks* cb)
	/* Do fancy stuff */
	if (something_relevant)
		cb->end = my_special_end; /* From now on, 

int my_special_end(const XMLNode* node, SAX_Callbacks* cb)
	/* Do something special for these special 'node' */
	if (something_not_relevant_anymore)
		cb->end = end; /* Go back to normal node end processing */

XMLDoc_parse_file_SAX("path_to_my_file.xml", &sax_callbacks, &sax_callbacks);

DOM parser

The DOM parser uses internally the SAX implementation with 6 specific callbacks. These callbacks are made available so that you can use them to load a whole XML document to memory but you would like to run some extra processing on the fly, as the document is being read.
In this case, you have to use the SAX parser and define your own callbacks to run your processing before calling the "official" DOM callbacks that will create the document DOM structure.
To achieve that, you HAVE TO use a DOM_through_SAX struct as the user pointer and initialize its 'doc' member with your initialized XMLDoc document and call the DOM callbacks with this.
Here is an example to compute nesting while the document is being DOM-style loaded.

int depth, max_depth;

int my_start(const XMLNode* node, struct _DOM_through_SAX* dom)
	if(++depth > max_depth) max_depth = depth;
	return DOMXMLDoc_node_start(node, dom);
int my_end(const XMLNode* node, struct _DOM_through_SAX* dom)
	return DOMXMLDoc_node_end(node, dom);
void test_DOM_from_SAX(void)
	DOM_through_SAX dom;
	SAX_Callbacks sax;
	XMLDoc doc;

	dom.doc = &doc;
	dom.current = NULL;
	sax.start_node = my_start;
	sax.end_node = my_end;
	sax.new_text = DOMXMLDoc_node_text;
	sax.all_event = NULL;
	depth = max_depth = 0;
	XMLDoc_parse_file_SAX("/home/matth/Code/tmp/big.xml", &sax, &dom);
	printf("Max depth: %d\n", max_depth);

It is also possible to parse a character buffer instead of a file, using the XMLDoc_parse_buffer_* instead of XMLDoc_parse_file_* functions.

Create an XML document

After an XML document has been initialized, you can start adding elements using the XMLDoc_add_node method.
Note that XMLNode objects should be allocated before being added. They can be "filled" either before or after insertion.
Use the XMLNode_alloc method to allocate XML nodes.

XMLDoc doc;
XMLNode* node;


node = XMLNode_alloc();
XMLNode_set_tag(node, "xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"");
XMLNode_set_type(node, TAG_INSTR);
XMLDoc_add_node(&doc, node);

node = XMLNode_alloc();
XMLNode_set_tag(node, " Pre-comment ");
XMLNode_set_type(node, TAG_COMMENT);
XMLDoc_add_node(&doc, node);

node = XMLNode_alloc();
XMLNode_set_tag(node, "\nAnother one\nMulti-line...\n");
XMLNode_set_type(node, TAG_COMMENT);
XMLDoc_add_node(&doc, node);

node = XMLNode_alloc();
XMLNode_set_tag(node, "properties");
XMLNode_set_type(node, TAG_FATHER);
XMLDoc_add_node(&doc, node); // Becomes root node

node = XMLNode_alloc();
XMLNode_set_type(node, TAG_COMMENT);
XMLNode_set_tag(node, "Hello World!");
XMLDoc_add_child_root(&doc, node);

node = XMLNode_alloc(1);
XMLNode_set_tag(node, "info");
XMLNode_set_text(node, "This is my name");
XMLNode_set_attribute(node, "type", "Name");
XMLDoc_add_child_root(&doc, node);
will produce the following XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- Pre-comment -->
Another one
        <!--Hello World!-->
	<info type="Name">This is my name</info>

Once the XML document has been created, it can be exported to a file with the XMLDoc_print method. It is possible to turn on/off different options to get a "pretty print" (human readable) using the tag_sep and child_sep parameters. It can be output to an already-opened file, that can be stdout if needed.

void XMLDoc_print(XMLDoc* doc, FILE* f, char* tag_sep, char* child_sep, int sz_line, int nb_char_tab);
  • tag_sep is a string that will be used to separate tags from each other. "\n" should be used for pretty print.
  • child_sep is a string that will be added to tag_sep to separate children tags from their father tag. "\t" should be used for pretty print.
Additional parameters can be provided to automatically split a tag on several lines according to a line size (the sz_line parameter), as well as specifying how many characters a tab should be accounted for (the nb_char_tab parameter).

Search in an XML document

The search can be performed on XMLNode structures, which is of course easier if the original document was read using the DOM function, or re-created by the user from the SAX callbacks.

XMLSearch_init should be called first on an XMLSearch structure to zero all members.
Then, use the XMLSearch_search_set_tag, XMLSearch_search_set_text and XMLSearch_search_add_attribute to specify one or more search criteria.

The XMLSearch structure is used to search through an XMLNode tree, using regexp-like:

  • tag will try to match a node tag. NULL or empty-string will not use the tag to test nodes so any node can match.
    Use the XMLSearch_search_set_tag function to set the search regexp for the tag.
  • text will try to match a node text. NULL will not use the text to test nodes so any node can match.
    Use the XMLSearch_search_set_text function to set the search regexp for the text.
  • attributes will be filled by the XMLSearch_search_add_attribute where is specified the attribute name and potentially value. If value is NULL, only the attribute presence is checked. An empty-string as a value is valid and will match an attribute name with an empty value (e.g. name="").
Match on names and values is made using a regexp-like string. It does not fully comply to usual regexps and so far, only '?' (any single character) and '*' (any possibly-empty string) are available but it is possible to use a custom function by calling XMLSearch_set_regexpr_compare. The given function takes the string to test and the pattern to match and should return true whenever the string matches the pattern.
The '\' character can be used to escape the next one.

Use the XMLSearch_next function to start searching for the first matching node. The first parameter is the node where to start the search from. Search will be made inside the whole children tree.
Next matching node is found by calling XMLSearch_next using the last matching node as a start.
NULL is returned when no more matching node are found inside the original from node hierarchy.
BE CAREFUL! The initial from node is not tested! It has to be tested separately with the XMLSearch_node_matches function.

NB: If you do not need search capabilities, you can remove the sxmlsearch.c from your project, saving 6 Kb! :-)

XMLDoc doc;
XMLSearch search;
XMLNode* node;

XMLDoc_parse_file_DOM("my_xml_file.xml", &doc);

XMLSearch_search_set_tag(&search, "month*");
XMLSearch_search_add_attribute(&search, "presence", NULL);
XMLSearch_search_add_attribute(&search, "value", "a*");

node = doc.nodes[doc.i_root];
if (XMLSearch_node_matches(node, &search))
	printf("Found match: <%s>\n", node->tag);
while ((node = XMLSearch_next(node, &search)) != NULL) {
	printf("Found match: <%s>\n", node->tag);


XPath-like queries can be used to initialize a search struct. It does not totally comply to
XPath grammar but can be used as an easier way to create a search tree.
Like in XPath, search on children is performed by using '/' as a separator.
Call XMLSearch_init_from_XPath to create a search tree from an XPath query.

tagFather[@name, @id!='0', .='toto*']/tagChild[.='search *', @attrib='val'] will be searching for node of tag "tagChild" and text is "search *", having an attribute named "attrib" which value is "val".
Additionally, these nodes should have as a father a node of tag "tagFather" with an attribute named "name" of any value, another attribute named "id" which value should not be "0" and with text starting with "toto".
	<tagFather id="1" name="Pere">toto et tata
		<tagChild attrib="val">search some text</tagChild>

Handle new tags

As sxmlc does not handle all W3C XML tags, you can specify your own tags so that they can be interpreted instead of aborting with a "Syntax error"! ;-)
Such "user tags" are defined through the XML_register_user_tag with 3 information:
  • The tag_type which is a number uniquely identifying the type of tag.
    It HAS TO be at least TAG_USER or the tag cannot be registered. However, no check is performed for duplicate so you can specify twice the same tag number (but why would you? ;-)).
  • The start and end are strings that are to be looked for respectively after '<' and before '>'
When parsing such nodes, the whole text between start and end strings will be stored in the 'tag' member of an XMLNode. The text itself is kept "as is" but you can remove potential escape characters with the str_unescape function.

NB: Internally, that is how comments, processing instructions and CDATA are handled.

XML_register_user_tag(TAG_USER+1, "<#[MYTAG-", "-]>");
XML_parse_1string("<#[MYTAG-Hello, World!-]>", &node);
printf(node.tag); /* Will display "Hello, World!" */
	<#[MYTAG-Hello, World!-]>

Project Web Hosted by

©Copyright 1999-2010 - Geeknet, Inc., All Rights Reserved

About - Legal - Help