libxml2操作2-获取属性值

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

文件内容如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员如山石

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值