libxml2操作1-获取关键字的内容


这里的例子都是依据当前libxml2的官网上的

官网地址如下:

Libxml Tutorial

这一个例子,实现了,从xml当中获取关键字的内容,关键字,对应着xml<>里面的内容,如下所示:

下面举个例子:



  
    John Fleck
    June 2, 2002
    example keyword
  
  
    This is the headline
    This is the body text.
  

 目的:获取name为“keyword”,所对应的值,或者说是字符串:“example keyword”

具体代码实现如下:


  1 #include 
  2 #include 
  3 #include 
  4 #include 
  5 #include 
  6 
  7 void
  8 parseStory (xmlDocPtr doc, xmlNodePtr cur) {
  9 
 10   xmlChar *key;
 11   cur = cur->xmlChildrenNode;
 12   while (cur != NULL) {
 13       if ((!xmlStrcmp(cur->name, (const xmlChar *)"keyword"))) {
 14         key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
 15         printf("keyword: %s\n", key);
 16         xmlFree(key);
 17       }
 18   cur = cur->next;
 19   }
 20     return;
 21 }
 22 
 23 static void
 24 parseDoc(char *docname) {
 25 
 26   printf("enter function parseDoc\r\n");
 27   xmlDocPtr doc;
 28   xmlNodePtr cur;
 29 
 30   doc = xmlParseFile(docname);
 31 
 32   if (doc == NULL ) {
 33     fprintf(stderr,"Document not parsed successfully. \n");
 34     return;
 35   }
 36   
 37   cur = xmlDocGetRootElement(doc);
 38   
 39   if (cur == NULL) {
 40     fprintf(stderr,"empty document\n");
 41     xmlFreeDoc(doc);
 42     return;
 43   } 
 44   
 45   if (xmlStrcmp(cur->name, (const xmlChar *) "story")) {
 46     fprintf(stderr,"document of the wrong type, root node != story");
 47     xmlFreeDoc(doc);
 48     return;
 49   } 
 50   
 51   cur = cur->xmlChildrenNode;
 52   while (cur != NULL) {
 53     if ((!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo"))){
 54       parseStory (doc, cur);
 55     } 
 56      
 57   cur = cur->next;
 58   }
 59   
 60   xmlFreeDoc(doc);
 61   printf("exit function parseDoc\r\n");
 62   return;
 63 } 
 64 
 65 int
 66 main(int argc, char **argv) {
 67 
 68   char *docname;
 69 
 70   if (argc <= 1) {
 71     printf("Usage: %s docname\n", argv[0]);
 72     return(0);
 73   }
 74 
 75   docname = argv[1];
 76   parseDoc (docname);
 77 
 78   return (1);
 79 }

下面是代码的编译:

root@mkx:~/workspace/libxml2/learn.20211112# gcc -o exampleC exampleC.c -L/usr/local/lib -lxml2 -L/usr/local/lib -lz -lm -ldl -I/usr/local/include/libxml2
root@mkx:~/workspace/libxml2/learn.20211112# ls
exampleC  exampleC.c  story.xml

下面是代码的运行情况:

root@mkx:~/workspace/libxml2/learn.20211112# ./exampleC story.xml 
keyword: example keyword

看,获取了keyword所对应的值:example keyword

你可能感兴趣的:(后端c)