I'm currently trying to recursively loop through a tree structure and serialize it to a string using (the language) C. I'm a real novice when it开发者_JAVA技巧 comes to C (Coming from a Java, C#, action-script background) and I'm having trouble getting to grips with things in general.
Should I use a library to help generate the XML? How do I implement recursion using C?
Thanks
Should I use a library to help generate the XML?
Yes. libxml, minixml and others. Just google to know others, but I'd go with libxml.
How do I implement recursion using C?
Well, implementing recursion itself is really simple. For example, this is recursive:
int fact(int i)
{
return i ? i*fact(i-1) : 1;
}
The problem comes with how complex you want to be. But for XML, use a library.
Using libxml, it could go like this:
#include <libxml/tree.h>
typedef struct _node
{
int value;
int childrenCount;
struct _node *children;
} node;
char buff[256];
node* createTree()
{
// some code to create the tree
}
// build XML for the tree recursively
void buildXml(xmlNodePtr xmlNodeParent, node *treeNode)
{
int i;
xmlNodePtr xmlNode = xmlNewChild(xmlNodeParent, NULL, BAD_CAST "node", NULL);
sprintf(buff, "%i", treeNode->value);
xmlNewProp(xmlNode, BAD_CAST "value", BAD_CAST buff);
for (i = 0; i < treeNode->childrenCount; i++)
{
buildXml(xmlNode, &treeNode->children[i]);
}
}
xmlDocPtr createDoc(node* treeRoot)
{
xmlDocPtr doc = NULL;
xmlNodePtr rootNode = NULL;
doc = xmlNewDoc(BAD_CAST "1.0");
rootNode = xmlNewNode(NULL, BAD_CAST "tree");
xmlDocSetRootElement(doc, rootNode);
buildXml(rootNode, treeRoot);
return doc;
}
int main()
{
node *root;
xmlDocPtr xmlDoc;
root = createTree();
xmlDoc = createDoc(root);
// print the result to console
xmlSaveFormatFileEnc("-", xmlDoc, "UTF-8", 1);
}
This code uses a general n-ary tree. If your tree is binary, the code would be almost the same.
精彩评论