標籤:else getc 代碼 style libxml mem creat sed turn
1、cJSON
cJSON.h cJSON.c(查看檔案)
2、libxml2
代碼如下:
#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"); return NULL; } cur = xmlDocGetRootElement(doc); if(NULL == cur) { fprintf(stderr, "Document is empty!\n"); xmlFreeDoc(doc); return NULL; } return cur; }void printXmlChildren(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 ;}void xml2json(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 ;}int main(int argc, char* 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, "解析XML資料失敗\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 ;}
運行結果:
存在問題:
1、JSON資料的格式,無法判斷整數等其他資料格式
2、XML迴圈資料的處理,XML迴圈資料轉換後應該是帶中括弧的
xml轉json