为了解析xml,可以使用Linux下默认安装的libxml2。
/*
a.c
功能:利用libxml2解析xml文件
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
int GetCurFilePath(char *lpOut) // get full path of the executable file
{
char chPath[BUFSIZ] = {0};
int nRetVal = readlink("/proc/self/exe", chPath, sizeof(chPath)); // get full path of the current-executable file
if(nRetVal < 0)
{
strcpy(lpOut, ".");
return -1;
}
else
{
strcpy(lpOut, chPath);
return 0;
}
}
int GetCurDir(char *lpOut) // get directory-path of current executable-file
{
char chPath[BUFSIZ] = { 0 };
if( GetCurFilePath(chPath) < 0 )
return - 1;
dirname(chPath); // dirname will change value of "chPath"(contain result)
strcpy(lpOut, chPath); // copy result to out-param
return 0;
}
xmlDocPtr getdoc(char *docname) // 根据文件名得到文档指针
{
xmlDocPtr doc;
doc = xmlParseFile(docname);
if(doc == NULL)
{
fprintf(stderr, "Document not parsed successfully.\n");
return NULL;
}
return doc;
}
// 在文档doc中解析xpath表达式,返回结果集指针
xmlXPathObjectPtr getnodeset(xmlDocPtr doc, xmlChar *xpath)
{
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
context = xmlXPathNewContext(doc);
if(context == NULL)
{
printf("Error in xmlXPathNewContent\n");
return NULL;
}
result = xmlXPathEvalExpression(xpath, context); // 在context中解析表达式xpath
xmlXPathFreeContext(context); // 释放context
if(result == NULL)
{
printf("Error in xmlXPathEvalExpression\n");
return NULL;
}
if(xmlXPathNodeSetIsEmpty(result->nodesetval)) // 解析表达式的结果集为空
{
xmlXPathFreeObject(result);
printf("No result\n");
return NULL;
}
return result;
}
// 解析xmlPath路径的结点
void testReadXmlDoc(char *filepath, char *xmlPath)
{
xmlDocPtr doc = getdoc(filepath);
if(NULL == doc)
return ;
xmlChar *xpath = (xmlChar*) xmlPath;
xmlXPathObjectPtr result = getnodeset(doc, xpath); // 获取结果集
if(result)
{
xmlNodeSetPtr n