在實際的開發過程中,我們常常需要把XML文件轉換成JSON格式的數據來處理。下面是一個示例代碼:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libxml/xmlmemory.h> #include <libxml/parser.h> #include <jansson.h> static json_t *xml_to_json(xmlNode *node); int main(int argc, char **argv) { xmlDoc *doc = NULL; xmlNode *root_element = NULL; json_t *json = NULL; char *json_str = NULL; if (argc != 2) { printf("Usage: %s file-name\n", argv[0]); return -1; } doc = xmlReadFile(argv[1], NULL, 0); if (doc == NULL) { printf("Error: could not parse file %s\n", argv[1]); return -1; } root_element = xmlDocGetRootElement(doc); json = xml_to_json(root_element); xmlFreeDoc(doc); xmlCleanupParser(); json_str = json_dumps(json, JSON_INDENT(2)); printf("%s", json_str); free(json_str); json_decref(json); return 0; } static json_t *xml_to_json(xmlNode *node) { xmlNode *curr = NULL; json_t *result = NULL, *children = NULL, *val = NULL; curr = node; while (curr != NULL) { if (curr->type == XML_ELEMENT_NODE) { if (result == NULL) { result = json_object(); } if (curr->children == NULL || curr->children->type == XML_TEXT_NODE) { val = json_string(""); } else { val = xml_to_json(curr->children); } if (json_object_get(result, curr->name) == NULL) { json_object_set(result, curr->name, val); } else { children = json_object_get(result, curr->name); if (json_typeof(children) != JSON_ARRAY) { children = json_array(); json_array_append(children, json_object_get(result, curr->name)); json_object_set(result, curr->name, children); } json_array_append(children, val); } } curr = curr->next; } return result; }
上述代碼使用了libxml和jansson兩個庫,其中libxml庫用于解析XML文件,而jansson庫用于生成JSON格式的數據。在代碼中,我們通過xml_to_json函數進行XML文件轉JSON格式數據的處理。該函數遍歷所有的XML節點,把節點的名稱和值轉換成JSON格式的鍵值對或者數組形式,最終通過json_dumps函數把JSON格式的數據轉換成字符串并打印出來。
上一篇vue響應式單位