I think I've *almost* got this. 

I define a structure that maps elements in a struct to an XML node name and
sprintf formatting code, like this:

bt_xml_node infohash_nodes[] =
{
 { "Filename", "%s", (int)(&new_bt_infohash.filename) - (int)(&new_bt_infohash) 
},
 { "Filesize", "%llu", (int)(&new_bt_infohash.filesize) - 
(int)(&new_bt_infohash) },
 { NULL, NULL, NULL }
};

Then I use some functions (attached) to use these structures to iterate
through a CStruct and create an XML node tree. Ideally, I'm going to use the
same structures to load the information from XML back into CStructs.

Is there a better / more standard way to do this? I'm happy with this
approach, except right now it seems like I need bunch of crappy if/else's to
translate all the sprintf() formatting codes to data types (example
attached).

Thanks,
        Tyler

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <libbtt/libbtt.h>
#include <libbtt/util/util.h>

#ifdef BTT_WITH_LIBXML2
#include <libxml/tree.h>

static xmlChar __buffer[255];

xmlNodePtr bt_data2xml(xmlNodePtr parent, bt_xml_node description, void* data) {
    if(!strcmp(description.format, "%s")) {
        strcpy((char*)__buffer, (char*)data);
    } else if(!strcmp(description.format, "%llu")) {
        sprintf((char*)__buffer, description.format, *((u_int64_t*)data));
    } else if(!strcmp(description.format, "%lu")) {
        sprintf((char*)__buffer, description.format, *((time_t*)data));
    } else if(!strcmp(description.format, "%u")) {
        sprintf((char*)__buffer, description.format, *((u_int32_t*)data));
    }

    return xmlNewTextChild(parent, NULL, description.name, __buffer);    
}

void bt_struct2xml(xmlNodePtr parent, bt_xml_node* items, void* start) {
    int i;
    for(i=0;items[i].name;i++) {
        bt_data2xml(parent, items[i], start + items[i].offset);
    }
    return;
}
#endif /* BTT_WITH_LIBXML2 */
#ifndef __BT_XML_H
#define __BT_XML_H
#include <libbtt/libbtt.h>
#include <libxml/tree.h>
#ifdef BTT_WITH_LIBXML2

typedef struct bt_xml_node {
    xmlChar*    name;
    char*       format;
    int         offset;
} bt_xml_node;

#endif /* BTT_WITH_LIBXML2 */
#endif /* __BT_XML_H */
_______________________________________________
xml mailing list, project page  http://xmlsoft.org/
[email protected]
http://mail.gnome.org/mailman/listinfo/xml

Reply via email to