1, Cjson
CJSON.h cjson.c (view file)
2, LIBXML2
The code is as follows:
#include <stdlib.h>#include<string.h>#include<stdio.h>#include<libxml/xmlmemory.h>#include<libxml/parser.h>#include"cJSON.h"xmlnodeptr Parsedoc (Const Char*DocName) {Xmldocptr doc; Xmlnodeptr cur; Xmlkeepblanksdefault (0); Doc=Xmlparsefile (DocName); if(NULL = =doc) {fprintf (stderr,"Document parsed failed!\n"); returnNULL; } cur=Xmldocgetrootelement (DOC); if(NULL = =cur) {fprintf (stderr,"Document is empty!\n"); Xmlfreedoc (DOC); returnNULL; } returncur; }voidPrintxmlchildren (xmlnodeptr xml_root) {xmlnodeptr cur=NULL; for(cur = xml_root; cur; cur = cur->next) { if(Cur->type = =Xml_element_node) { if(Cur->children->type = =xml_text_node) fprintf (stdout,"node:[%s][%s]\n", cur->name, xmlnodegetcontent (cur)); Else if(Cur->children->type = =Xml_element_node) {fprintf (stdout,"node:[%s]\n", cur->name); Printxmlchildren (cur-children); } } } return ;}voidXml2json (xmlnodeptr xml_root, cjson**json_root) {xmlnodeptr Xml_cur=NULL; Cjson*json_cur =NULL; for(xml_cur = xml_root; xml_cur; xml_cur = xml_cur->next) { if(Xml_cur->type = =Xml_element_node) { if(Xml_cur->children->type = =Xml_text_node) {//fprintf (stdout, "1--->[%s]\n", xml_cur->name);Json_cur =cjson_createstring (Xmlnodegetcontent (xml_cur)); Cjson_additemtoobject (*json_root, xml_cur->name, json_cur); } Else if(Xml_cur->children->type = =Xml_element_node) {//fprintf (stdout, "2--->[%s]\n", xml_cur->name);Json_cur =Cjson_createobject (); Cjson_additemtoobject (*json_root, xml_cur->name, json_cur); Xml2json (Xml_cur->children, &json_cur); } } } return ;}intMainintargcChar*argv[]) { Char*DocName; Xmlnodeptr Xml_root; if(1>=argc) {fprintf (stderr,"usage:%s docname!\n", argv[0]); return-1; } docname= argv[1]; if(NULL = = (Xml_root =Parsedoc (DocName))) {fprintf (stderr,"parsing XML data failed \ n"); return-1; } printxmlchildren (Xml_root); fprintf (stdout,"-------------------------------------\ n"); Cjson* Json_root =Cjson_createobject (); Xml2json (Xml_root,&json_root); fprintf (stdout,"json:\n[%s]\n", Cjson_print (json_root)); fprintf (stdout,"-------------------------------------\ n"); return ;}
Operation Result:
A problem exists:
1, JSON data format, cannot judge the integer and other data formats
2, XML loop data processing, XML loop data after conversion should be with brackets
XML to JSON