上一篇是获取了节点的值,这一次获取属性的值:

文件内容如下:

<?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>
<reference uri="storyuri_example1"/></story>

 例子如下:

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

开始编译:

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

开始运行:

root@mkx:~/workspace/libxml2/learn.20211112# ./example_Retrieviing story.xml
enter function getReference
uri: storyuri_example1
exit function getReference

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐