[libxml2]_[C/C++]_[使用libxml2读取分析xml文件]

 

场景:

1. xml文件大部分时候都是用来做配置用的, 而windows的msxml库又不是Windows自带的库,使用它得打包, 而且花时间学习这个独立于平台的库不划算.

2. libxml2是跨平台的xml库,和expat一样, MacOSX默认就支持它.

3. 以下是使用libxml2读取xml文件的例子, 注意,path路径要utf8编码, 不然识别不了中文路径.

4. 关于libxml2的vc编译看 libxml2-2.7.1\win32里的Readme文件.

5.注意,在使用libxml2库是,一定要在主进程的主线程调用初始化`xmlInitParser()`和结束进程前主线程释放`xmlCleanupParser()`.

test_libxml2.cpp

 

#include "stdafx.h"

#include <iostream>
#include "gtest/gtest.h"
#include "libxml/tree.h"
#include "libxml/parser.h"
#include "libxml/xpath.h"
#include "libxml/xpathInternals.h"

static void Parse(std::string path)
{
	xmlDocPtr doc = xmlParseFile(path.c_str());
	xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
	xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(BAD_CAST "/setting/url", xpathCtx);

	xmlNodeSetPtr vendors = xpathObj->nodesetval;
	
	for(int i = 0; i < vendors->nodeNr; ++i)
	{
		xmlNodePtr vendor = vendors->nodeTab[i];
		xmlNodePtr children = vendor->children;

		while(children)
		{
			//xmllib把上一个结束标签到下个开始标签之间当作一个Text node
			if(!xmlNodeIsText(children))
			{
				const char* name = (const char*)children->name;
				xmlChar* content1 = xmlNodeGetContent(children);
				char* content = (char*)content1;
				std::cout << "name: " << name << ":" << " content1:" << content1 << std::endl;
				xmlFree(content1);
			}
			children = children->next;
		}
	}
	
	xmlXPathFreeObject(xpathObj);
	xmlXPathFreeContext(xpathCtx);
	xmlFreeDoc(doc);
}

TEST(test_libxml2,test)
{
	Parse("..\\Debug\\Table.xml");
}

 

 

Table.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<setting>
   <url>
     <help>http://www.xxxx.com/online-help/56/</help>
     <purchase>http://www.xxxx.com/purchase/56.html</purchase>
     <support>http://www.xxxx.com/support.html</support>
     <brand>http://www.xxxx.com</brand>
     <update>http://www.xxxx.com/w</update>
     <product>http://www.xxxx.com/56.html</product>
   </url>
</setting>


输出:

 

 

Note: Google Test filter = test_libxml2.test
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from test_libxml2
[ RUN      ] test_libxml2.test
name: help: content1:http://www.xxxx.com/online-help/56/
name: purchase: content1:http://www.xxxx.com/purchase/56.html
name: support: content1:http://www.xxxx.com/support.html
name: brand: content1:http://www.xxxx.com
name: update: content1:http://www.xxxx.com/w
name: product: content1:http://www.xxxx.com/56.html
[       OK ] test_libxml2.test (2978 ms)

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Peter(阿斯拉达)

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

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

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

打赏作者

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

抵扣说明:

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

余额充值