场景:
1. xml文件大部分时候都是用来做配置用的, 而windows的msxml库又不是Windows自带的库,使用它得打包, 而且花时间学习这个独立于平台的库不划算.
2. libxml2是跨平台的xml库,和expat一样, MacOSX默认就支持它.
3. 以下是使用libxml2读取xml文件的例子, 注意,path路径要utf8编码, 不然识别不了中文路径.
4. 关于libxml2的vc编译看 libxml2-2.7.1\win32里的Readme文件.
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)