关于后端:libxml2操作1获取关键字的内容

49次阅读

共计 2035 个字符,预计需要花费 6 分钟才能阅读完成。


这里的例子都是根据以后 libxml2 的官网上的

官网地址如下:

Libxml Tutorial

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

上面举个例子:

<?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>

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

具体代码实现如下:


  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <stdlib.h>
  4 #include <libxml/xmlmemory.h>
  5 #include <libxml/parser.h>
  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

正文完
 0