据说tinyXml的效率不是很高,不过对于小型的配置文件来说一点点效率影响也没什么关系。
先看下用到的tinyXml中主要的类
TiXmlDocument: XML的文档类,相当于整个文档树的对象。
TiXmlDeclaration:XML文档的声明,对于下面一个XML来说就是这一段:<?xml version="1.0" encoding="utf-8"?>
TiXmlElement:XML节点对象,节点中包含attribute和text, 分别用getAttribute()和getText()函数获取。
目标XML:
<?xml version="1.0" encoding="utf-8"?> <conf> <ip>http://192.168.1.2</ip> <port>1777</port> <payurl>http://192.168.1.2</payurl> <payport>1888</payport> <version>1.0.1.4.11</version> </conf>
解析代码
TiXmlDocument* xmlDoc = new TiXmlDocument(); xmlDoc->LoadFile("conf.xml"); TiXmlElement* rootEle = xmlDoc->RootElement(); TiXmlElement* connectIpEle = rootEle->FirstChildElement(); TiXmlElement* connectPortEle = connectIpEle->NextSiblingElement(); TiXmlElement* payUrlEle = connectPortEle->NextSiblingElement(); TiXmlElement* payPortEle = payUrlEle->NextSiblingElement(); TiXmlElement* versionEle = payPortEle->NextSiblingElement(); TiXmlElement* md5Ele = versionEle->NextSiblingElement(); _ip = const_cast<char*>(connectIpEle->GetText()); _port = const_cast<char*>(connectPortEle->GetText()); _payUrl = const_cast<char*>(payUrlEle->GetText()); _payPort = const_cast<char*>(payPortEle->GetText()); _version = const_cast<char*>(versionEle->GetText()); _md5 = const_cast<char*>(md5Ele->GetText());