JSON和XML是兩種常用的數(shù)據(jù)格式,它們?cè)诓煌念I(lǐng)域有著不同的應(yīng)用。在某些情況下,需要將一個(gè)JSON文件轉(zhuǎn)換成XML格式,這時(shí)候就需要使用C語言來完成。
在C語言中,有很多庫可以用來操作JSON和XML文件。其中,常用的JSON庫是json-c庫,而常用的XML庫是libxml2庫。
下面是一個(gè)使用json-c庫將JSON文件轉(zhuǎn)換成XML文件的示例代碼:
#include <stdio.h>#include <json-c/json.h>#include <libxml/xmlwriter.h>void json_to_xml(json_object *json, xmlTextWriterPtr writer, const char *name) { xmlTextWriterStartElement(writer, BAD_CAST name); json_object_object_foreach(json, key, val) { switch (json_object_get_type(val)) { case json_type_object: json_to_xml(val, writer, key); break; case json_type_array: xmlTextWriterStartElement(writer, BAD_CAST key); for (int i = 0; i < json_object_array_length(val); i++) { json_object *item = json_object_array_get_idx(val, i); switch (json_object_get_type(item)) { case json_type_object: json_to_xml(item, writer, NULL); break; case json_type_array: xmlTextWriterStartElement(writer, BAD_CAST key); json_to_xml(item, writer, NULL); xmlTextWriterEndElement(writer); break; case json_type_string: xmlTextWriterWriteAttribute(writer, BAD_CAST "value", BAD_CAST json_object_get_string(item)); break; case json_type_int: case json_type_double: xmlTextWriterWriteAttribute(writer, BAD_CAST "value", BAD_CAST json_object_to_json_string(item)); break; } } xmlTextWriterEndElement(writer); break; case json_type_string: xmlTextWriterWriteString(writer, BAD_CAST json_object_get_string(val)); break; case json_type_int: case json_type_double: xmlTextWriterWriteAttribute(writer, BAD_CAST key, BAD_CAST json_object_to_json_string(val)); break; } } xmlTextWriterEndElement(writer); } int main() { const char *json_str = "{\"name\":\"張三\",\"age\":18,\"hobbies\":[\"basketball\",\"music\",\"reading\"],\"address\":{\"province\":\"廣東\",\"city\":\"深圳\"}}"; json_object *json = json_tokener_parse(json_str); xmlTextWriterPtr writer = xmlNewTextWriterFilename("output.xml", 0); xmlTextWriterStartDocument(writer, NULL, "UTF-8", NULL); json_to_xml(json, writer, "root"); xmlTextWriterEndDocument(writer); xmlFreeTextWriter(writer); json_object_put(json); return 0; }
在上述代碼中,我們首先使用json_tokener_parse函數(shù)將JSON字符串解析成json_object對(duì)象,然后使用xmlNewTextWriterFilename函數(shù)創(chuàng)建一個(gè)XML文件的寫入器。接著,我們調(diào)用json_to_xml函數(shù)將json_object對(duì)象轉(zhuǎn)換成XML格式,并寫入到文件中。最后,記得關(guān)閉寫入器和釋放json_object對(duì)象。
通過上述代碼,我們可以輕松地將一個(gè)JSON文件轉(zhuǎn)換成XML文件,并且可以根據(jù)需要靈活地添加或刪除某些字段,以滿足不同的需求。