本文介绍c++编写的xml解析库——pugixml,能解析xml内容,支持xpath解析,同时能够跨linux平台,非常方便。
总结一下使用步骤和简单的使用方法:
std::strFile = "../test.xml"; pugi::xml_document doc; if (!doc.load_file(strFile.c_str())) { return ;}
std::strText = "testing"; pugi::xml_document doc; if (!doc.load(strText.c_str())) { return ;}
<?xml version="1.0" encoding="utf-8" ?> <root> <!-- 输入参数配置 --> <form ip="10.2.134.243" port="80" action="sisserver.php"> <input name="data_type" value="POI" /> <input name="query_type" value="TQUERY" /> <input name="category" value="" /> <!-- 查询词的返回结果xpath配置 --> <xpath poiroot="//list/poi" idfield="pguid" namefield="name"/> <!-- 评分权重配置 r1~r4-期望结果的权重,n1~n10-实际查询结果的排名权重--> <weight> <!-- 查询词正常得分阀值 --> <threshold>3</threshold> <!-- 计算分数分布情况的步长值 --> <step>0.5</step> </weight> </root>读取代码:
std::string strFile = "/bak/workspace/test/src/params.xml"; pugi::xml_document doc; if (!doc.load_file(strFile.c_str())) {return 0;} pugi::xml_node form = doc.child("root").child("form"); std::string ip = form.attribute("ip").value(); std::string port = form.attribute("port").value(); char cBuf[2083]; sprintf(cBuf, "http://%s:%s/%s?", ip.c_str(), port.c_s()); std::string strTemp(cBuf); std::string m_strURLBase = strTemp; for (pugi::xml_node input = form.first_child(); input;input = input.next_sibling()) { std::string strValue = input.attribute("value").value(); if (!strValue.empty()) { std::string strName = input.attribute("name").value(); sprintf(cBuf, "%s=%s&", strName.c_str(), strValue.c_str()); std::string strTemp(cBuf); m_strURLBase += strTemp; } } //读取xpath pugi::xml_node xpath = doc.child("root").child("xpath"); std::string m_strPOIRoot = xpath.attribute("poiroot").value(); std::string m_strPOIID = xpath.attribute("idfield").value(); //读取评分权重 pugi::xml_node weight = doc.child("root").child("weight"); float m_fThred = atof(weight.child_value("threshold")); float m_fStep = atof(weight.child_value("step"));
<?xml version="1.0" encoding="utf-8" ?> <root> <list count="3" time"10"> <poi> <pguid>123</pguid> <name>xx1</name> </poi> <poi> <pguid>456</pguid> <name>xx2</name> </poi> <poi> <pguid>789</pguid> <name>xx3</name> </poi> </list> </root>
//从strWebContent内容中解析出pguid和name pugi::xml_document doc; pugi::xml_parse_result result = doc.load(strWebContent.c_str()); if (!result) {return -1;} pugi::xpath_node_set tools = doc.select_nodes(m_strPOIRoot.c_str()); for (pugi::xpath_node_set::const_iterator it = tools.begin(); it != tools.end(); ++it) { pugi::xpath_node node = *it; string strPOI = node.node().child_value(m_strPOIID.c_str()); string strName = node.node().child_value(m_strPOIName.c_str()); }
原文地址:http://blog.csdn.net/qingzai_/article/details/44982725