1 #include <opensrf/xml_utils.h>
4 static jsonObject* _xmlToJSON(xmlNodePtr node, jsonObject*);
6 void recurse_doc( xmlNodePtr node ) {
7 if( node == NULL ) return;
8 printf("Recurse: %s => %s", node->name, node->content );
9 xmlNodePtr t = node->children;
18 jsonObject* xmlDocToJSON(xmlDocPtr doc) {
20 return _xmlToJSON(xmlDocGetRootElement(doc), NULL);
23 static jsonObject* _xmlToJSON(xmlNodePtr node, jsonObject* obj) {
25 if(!node) return NULL;
26 if(xmlIsBlankNode(node)) return NULL;
27 if(obj == NULL) obj = jsonNewObject(NULL);
29 if(node->type == XML_TEXT_NODE) {
30 jsonObjectSetString(obj, (char*) node->content);
32 } else if(node->type == XML_ELEMENT_NODE || node->type == XML_ATTRIBUTE_NODE ) {
34 jsonObject* new_obj = jsonNewObject(NULL);
38 /* do the duplicate node / array shuffle */
39 if( (old = jsonObjectGetKey(obj, (char*) node->name)) ) {
40 if(old->type == JSON_ARRAY ) {
41 jsonObjectPush(old, new_obj);
43 jsonObject* arr = jsonNewObject(NULL);
44 jsonObjectPush(arr, jsonObjectClone(old));
45 jsonObjectPush(arr, new_obj);
46 jsonObjectSetKey(obj, (char*) node->name, arr);
49 jsonObjectSetKey(obj, (char*) node->name, new_obj);
52 xmlNodePtr child = node->children;
53 if (child) { // at least one...
54 if (child != node->last) { // more than one -- ignore TEXT nodes
56 if (child->type != XML_TEXT_NODE) _xmlToJSON(child, new_obj);
60 _xmlToJSON(child, new_obj);
69 char* xmlDocToString(xmlDocPtr doc, int full) {
79 xmlDocDumpMemory(doc, &xmlbuf, &size);
80 xml = strdup((char*) (xmlbuf));
86 xmlBufferPtr xmlbuf = xmlBufferCreate();
87 xmlNodeDump( xmlbuf, doc, xmlDocGetRootElement(doc), 0, 0);
88 xml = strdup((char*) (xmlBufferContent(xmlbuf)));
89 xmlBufferFree(xmlbuf);
98 char* xmlSaxAttr( const xmlChar** atts, const char* name ) {
101 for(i = 0; (atts[i] != NULL); i++) {
102 if(!strcmp((char*) atts[i], name)) {
103 if(atts[++i]) return (char*) atts[i];
111 int xmlAddAttrs( xmlNodePtr node, const xmlChar** atts ) {
114 for(i = 0; (atts[i] != NULL); i++) {
116 xmlSetProp(node, atts[i], atts[i+1]);