##安裝 libxmlhtml
libxml是一個用來解析XML文檔的函數庫。它用C語言寫成,而且能爲多種語言所調用node
###下載libxml 貌似libxml官方已經被河蟹掉了。不要緊這裏有 libxml的下載地址 2.7.4函數
###下載以後解壓 tar -zxvf libxml2-2.7.4.tar.gz測試
##寫測試代碼.net
###生成xml的代碼unix
int main(int argc, char **argv) { xmlDocPtr doc = NULL; xmlNodePtr root_node = NULL, node = NULL, node1 = NULL; doc = xmlNewDoc(BAD_CAST "1.0"); root_node = xmlNewNode(NULL, BAD_CAST "root"); xmlDocSetRootElement(doc, root_node); xmlNewChild(root_node, NULL, BAD_CAST "node1",BAD_CAST "content of node1"); node=xmlNewChild(root_node, NULL, BAD_CAST "node3",BAD_CAST"node has attributes"); xmlNewProp(node, BAD_CAST "attribute", BAD_CAST "yes"); node = xmlNewNode(NULL, BAD_CAST "node4"); node1 = xmlNewText(BAD_CAST"other way to create content"); xmlAddChild(node, node1); xmlAddChild(root_node, node); xmlSaveFormatFileEnc(argc > 1 ? argv[1] : "-", doc, "UTF-8", 1); xmlFreeDoc(doc); xmlCleanupParser(); xmlMemoryDump(); return(0); }
gcc -I /usr/local/include/libxml2 -L /usr/local/lib -lxml2 test.c -o test
./test
新建待解析xml, 文件內容:code
<?xml version="1.0"?> <story> <storyinfo> <author>John Fleck</author> <datewritten>June 2, 2002</datewritten> <keyword>example keyword</keyword> </storyinfo> <body> <headline>This is the headline</headline> <para>This is the body text.</para> </body> </story>
###解析的c語言代碼orm
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <libxml/xmlmemory.h> #include <libxml/parser.h> void parseStory (xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"keyword"))) { key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1); printf("keyword: %s\n", key); xmlFree(key); } cur = cur->next; } return; } static void parseDoc(char *docname) { xmlDocPtr doc; xmlNodePtr cur; doc = xmlParseFile(docname); if (doc == NULL ) { fprintf(stderr,"Document not parsed successfully. \n"); return; } cur = xmlDocGetRootElement(doc); cur = xmlDocGetRootElement(doc); if (cur == NULL) { fprintf(stderr,"empty document\n"); xmlFreeDoc(doc); return; } if (xmlStrcmp(cur->name, (const xmlChar *) "story")) { fprintf(stderr,"document of the wrong type, root node != story"); xmlFreeDoc(doc); return; } cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo"))){ parseStory (doc, cur); } cur = cur->next; } xmlFreeDoc(doc); return; } int main(int argc, char **argv) { char *docname; if (argc <= 1) { printf("Usage: %s docname\n", argv[0]); return(0); } docname = argv[1]; parseDoc (docname); return (1); }
###編譯 gcc keyword.c -o keyword -I/usr/local/include/libxml2 -lxml2xml
###運行 ./keyword story.xmlhtm
參考博文
http://blog.csdn.net/z507263441/article/details/17742727 http://www.cnblogs.com/shanzhizi/archive/2012/07/09/2583739.html