#include <libxml/xmlreader.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <stdlib.h>
#define TEST
char * get_xml_value(xmlTextReaderPtr reader); char * get_xml_key(xmlTextReaderPtr reader); int parse_xml(const char *xml_buf, int xml_buf_size);
#ifdef TEST int main() {
char *xml_buf = "<xmlTest xmlns=/"http://www.openuri.org//"><userName>1234567</userName><dstFolder>dddd</dstFolder><subject>test</subject></xmlTest>"; parse_xml(xml_buf, strlen(xml_buf)); /*這裡只是測試,不對傳回值做判斷*/ return 0; } #endif
/*分解提交過來的XML串,當然也可以是一個檔案,只要更改相關調用函數*/ int parse_xml(const char *xml_buf, int xml_buf_size) { int ret = 0; int node_depth = 0; int node_type = 0; xmlTextReaderPtr xml_reader;
xml_reader = xmlReaderForMemory(xml_buf, xml_buf_size, NULL, NULL, 0); if (NULL == xml_reader) { return -1; }
while (1 == (ret = xmlTextReaderRead(xml_reader))) {
/* 這塊是判斷節點深度的,您可以對分解深度做一個限制 node_depth = xmlTextReaderDepth(xml_reader); if (5 < node_depth) { ret = -2; break; } */
/*判斷當前節點的類型*/ node_type = xmlTextReaderNodeType(xml_reader); switch(node_type) { case 1: get_xml_key(xml_reader); break; case 3: get_xml_value(xml_reader); break;
} }
xmlFreeTextReader(xml_reader); return ret; }
/*取得當前節點的KEY值*/ char * get_xml_key(xmlTextReaderPtr reader) { const xmlChar *key; key = xmlTextReaderConstName(reader); if (NULL == key) { return NULL; } printf("KEY : %s/n", key); } /*取得當前節點的VALUE值*/ char * get_xml_value(xmlTextReaderPtr reader) { const xmlChar *value;
value = xmlTextReaderConstValue(reader); if (NULL == value) { return NULL; } printf("VALUE : %s/n", value); }
|