/* * SXML: sample program to parse XML file * $Id: sxmlparse.c,v 1.4 2007/08/31 09:57:49 kouichi Exp $ */ #include #include #include #include #include #include "sxml.h" #define TEST_XML "test.xml" #define TAG_ROOT "config" #define ROOT_ATTR_NAME "type" #define ROOT_ATTR_VALUE "smtp" #define TAG_SERVER "server" #define TAG_ADDRESS "address" #define TAG_COMMENT "comment" #define TAG_PORT "port" static void parse_error(const char *); static void parse_server(sxml_node_t *); static void parse_root(sxml_node_t *); static void parse_prolog(sxml_node_t *); static void parse_error(name) const char * name; { fprintf(stderr, "WARN: unknown tag: %s\n", name); } static void parse_server(node) sxml_node_t * node; { if (node != NULL) { sxml_node_t * np; for (np = node; np != NULL; np = sxml_get_next_sibling(np)) { const char * content; if (sxml_get_type(np) != SXML_ELEMENT) { continue; } if (sxml_get_element_name(np) == NULL) { continue; } content = sxml_get_content(sxml_get_child(np)); if (strcmp(sxml_get_element_name(np), TAG_ADDRESS) == 0) { fprintf(stdout, "address: %s\n", content); } else if (strcmp(sxml_get_element_name(np), TAG_PORT) == 0) { fprintf(stdout, "port: %s\n", content); } else if (strcmp(sxml_get_element_name(np), TAG_COMMENT) == 0) { fprintf(stdout, "comment: %s\n", content); } else { parse_error(sxml_get_element_name(np)); } } } } static void parse_root(root) sxml_node_t * root; { sxml_node_t * node; node = sxml_find_element(root, TAG_ROOT, ROOT_ATTR_NAME, ROOT_ATTR_VALUE); if (node != NULL) { sxml_node_t * np; for (np = sxml_get_child(node); np != NULL; np = sxml_get_next_sibling(np)) { const char * content; if (sxml_get_type(np) != SXML_ELEMENT) { continue; } if (sxml_get_element_name(np) == NULL) { continue; } content = sxml_get_content(sxml_get_child(np)); if (strcmp(sxml_get_element_name(np), TAG_SERVER) == 0) { parse_server(sxml_get_child(np)); } else { parse_error(sxml_get_element_name(np)); } } } } static void parse_prolog(root) sxml_node_t * root; { sxml_node_t * node; node = sxml_find_prolog(root, "xml"); if (node != NULL) { const char * val; val = sxml_get_attribute(node, "version"); if (val != NULL) { fprintf(stdout, "XML version: %s\n", val); } val = sxml_get_attribute(node, "encoding"); if (val != NULL) { fprintf(stdout, "XML encoding: %s\n", val); } } } int main(argc, argv) int argc; char * argv[]; { int fd; fd = open(TEST_XML, O_RDONLY, 0400); if (fd != -1) { sxml_node_t * root; root = sxml_parse_file(fd); if (root != NULL) { parse_prolog(root); parse_root(root); sxml_delete_node(root); } close(fd); } return 0; }