window下使用libxml2读取xml文件

1 进入http://xmlsoft.org/sources/win32/页面下载以下软件包


2 解压3个软件包

将libxml2-2.6.22.win32/include下的libxml目录拷到项目的include目录里下

将iconv-1.9.2.win32/include下的iconv.h拷到项目的include目录里下

将3个解压软件包的lib目录拷贝到项目下

3 添加项目包含目录include 和附加库目录lib

4 将各软件包解压后的lib目录下的libxml2.dlliconv.dll zlib.dll拷贝到exe程序的运行目录

5 测试文件为:

window下使用libxml2读取xml文件_第1张图片

6 测试代码:

#include <stdio.h>
#include <iostream>
#include <Windows.h>  
#include "libxml\parser.h"
#include "libxml\tree.h"
#include "iconv.h"

#pragma comment(lib, "libxml2.lib")   
#pragma comment(lib, "iconv.lib")  
using namespace std;

xmlChar* ReadXml(char* filename,char* node_content);

int main(int argc,char* argv[])
{
	char *str1 = (char*)ReadXml("myxml.xml","to");
	printf("to:%s\n",str1);

	char *str2 = (char*)ReadXml("myxml.xml","body");
	printf("body:%s\n",str2);

	system("pause");
}

xmlChar* ReadXml(char* filename,char* node_content)
{
	xmlDocPtr doc;           //定义解析文档指针
    xmlNodePtr node;          //定义结点指针(你需要它为了在各个结点间移动)
	xmlKeepBlanksDefault(0);  //避免将空格当作一个节点
	doc = xmlParseFile(filename);

	if(doc == NULL)
	{
		fprintf(stderr,"parse error\n");
		exit(1);
	}
	node = xmlDocGetRootElement(doc);
	if(node == NULL)
	{
		fprintf(stderr, "doc has no content\n");
	}
	char str[256]={0};
	node = node->children;
	while(node != NULL)
	{
		if(xmlStrcmp(node->name,(const xmlChar*)node_content)==0)
		{
			return xmlNodeGetContent(node);
		}
		
		node = node->next; 
	}
	xmlFreeDoc(doc);
	return NULL;
}

7 运行结果:





你可能感兴趣的:(c,libxml2,xml读取)