我目前正在尝试递归地遍历树结构,并使用(语言) C将其序列化为字符串。对于C语言,我是一个真正的新手(来自Java,C#,动作脚本背景),而且我在掌握一般的东西方面遇到了困难。
我应该使用库来帮助生成XML吗?如何使用C实现递归?
谢谢
发布于 2011-07-20 07:18:42
发布于 2011-07-21 04:00:07
使用libxml,它可能是这样的:
#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);
}这段代码使用了通用的n元树。如果你的树是二进制的,那么代码几乎是一样的。
https://stackoverflow.com/questions/6755184
复制相似问题