关于后端:libxml2操作2获取属性值

34次阅读

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

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

文件如下:

<?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");

编译如下:

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@maokx:~/workspace/libxml2/learn.20211112# ./example_Retrieviing story.xml
enter function getReference
uri: storyuri_example1
exit function getReference

正文完
 0