C tree XML serialization

﹥>﹥吖頭↗ 提交于 2019-12-24 20:25:33

问题


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 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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6755184/c-tree-xml-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!