varch/test/test_xml.c
2024-11-16 13:36:54 +08:00

132 lines
2.5 KiB
C

#include <stdio.h>
#include <string.h>
#if defined(TEST_TARGET_xml)
#include <varch/command.h>
#include <varch/xml.h>
#else
#include "init.h"
#include "command.h"
#include "xml.h"
#endif
#define READ_FILE "test/file/read.xml"
#define WRITE_FILE "test/file/write.xml"
static void test_read(void)
{
xml_t root, x;
root = xml_file_load(READ_FILE);
if (!root) return;
printf("load success!\r\n");
x = xml_to(root, "book", 1);
printf("x attr: %s\r\n", xml_get_attribute(x, NULL, 0));
x = xml_to(x, "author", 0);
printf("author: %s\r\n", xml_get_text(x));
xml_delete(root);
}
static void test_write(void)
{
xml_t root, x;
root = xml_create("root");
if (!root) return;
x = xml_create("name");
xml_set_text(x, "xml parser");
xml_insert(root, 0, x);
x = xml_create("description");
xml_set_text(x, "This is a C language version of xml parser.");
xml_insert(root, 1, x);
x = xml_create("license");
xml_set_text(x, "GPL3.0");
xml_insert(root, 2, x);
char *s = xml_dumps(root, 1, 0, NULL);
if (s)
{
printf(s);
free(s);
}
xml_file_dump(root, WRITE_FILE);
xml_delete(root);
}
static void usage(void)
{
printf(
"Usage: xml [opt] [arg]\n"
"\n"
"options:\n"
" -h Print help\n"
" -v Print version\n"
"\n"
"argument:\n"
" <read> Test default read function\n"
" <write> Test default write function\n"
);
}
static int test(int argc, char *argv[])
{
/* reset getopt */
command_opt_init();
while (1)
{
int opt = command_getopt(argc, argv, "hv");
if (opt == -1) break;
switch (opt)
{
case 'v' :
printf("xml version %d.%d.%d\r\n", XML_V_MAJOR, XML_V_MINOR, XML_V_PATCH);
return 0;
case '?':
printf("Unknown option `%c`\r\n", command_optopt);
return -1;
case 'h' :
default:
usage();
return 0;
}
}
for (int index = command_optind; index < argc; index++)
{
if (!strcmp(argv[index], "read"))
{
test_read();
}
else if (!strcmp(argv[index], "write"))
{
test_write();
}
}
return 0;
}
#if defined(TEST_TARGET_xml)
int main(int argc, char *argv[])
{
return test(argc, argv);
}
#else
void test_xml(void)
{
command_export("xml", test);
}
init_export_app(test_xml);
#endif