示例文档story.xml如下:
- <?xmlversion="1.0"?>
- <story>
- storyinfo>
- author>JohnFleck</datewritten>June2,2002keyword>examplekeywordbodyheadline>Thisistheheadlinepara>Thisisthebodytext.>
解析文档时只需要文档名和一个函数调用,再加上错误处理。下面代码查找keyword节点并打印节点下的文本内容,如下:
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- #include<libxml/xmlmemory.h>
- #include<libxml/parser.h>
- /*解析storyinfo节点,打印keyword节点的内容*/
- voidparseStory(xmlDocPtrdoc,xmlNodePtrcur){
- xmlChar*key;
- cur=cur->xmlChildrenNode;
- while(cur!=NULL){
- /*找到keyword子节点*/
- if(!xmlStrcmp(cur->name,(constxmlChar*)"keyword")){
- key=xmlNodeListGetString(doc,cur->xmlChildrenNode,1);
- printf("keyword:%s\n",key);
- xmlFree(key);
- }
- cur=cur->next;/*下一个子节点*/
- return;
- }
- /*解析文档*/
- staticvoidparseDoc(char*docname){
- /*定义文档和节点指针*/
- xmlDocPtrdoc;
- xmlNodePtrcur;
- /*进行解析,如果没成功,显示一个错误并停止*/
- doc=xmlParseFile(docname);
- if(doc==NULL){
- fprintf(stderr,"Documentnotparsesuccessfully.\n");
- return;
- /*获取文档根节点,若无内容则释放文档树并返回*/
- cur=xmlDocGetRootElement(doc);
- if(cur==NULL){
- fprintf(stderr,"emptydocument\n");
- xmlFreeDoc(doc);
- /*确定根节点名是否为story,不是则返回*/
- if(xmlStrcmp(cur->name,153); background-color:inherit; font-weight:bold">constxmlChar*)"story")){
- "documentofthewrongtype,rootnode!=story");
- xmlFreeDoc(doc);
- /*遍历文档树*/
- cur=cur->xmlChildrenNode;
- while(cur!=NULL){
- /*找到storyinfo子节点*/
- constxmlChar*)"storyinfo")){
- parseStory(doc,cur);/*解析storyinfo子节点*/
- cur=cur->next;/*下一个子节点*/
- xmlFreeDoc(doc);/*释放文档树*/
- intmain(intargc,char**argv){
- char*docname;
- if(argc<=1){
- printf("Usage:%sdocname\n",argv[0]);
- return0;
- docname=argv[1];
- parseDoc(docname);
- return1;
- }