基于pugixml开源解析库的XML文档构建和解析
Pugixml是与tinyxml、slimxml相类似的一个开源XML解析器,能支持C++,并可以在Windows与Linux下编译。Pugixml支持包括Unicode在内的多种字符集(tinyxml不支持Unicode),但是其中文帮助文档很少,只能在googlecode上找到http://pugixml.googlecode.com/svn/tags/latest/docs/quickstart.html这个英文文档,研究了其中部分,将一些基本操作贴出来分享下: 首先需要将pugixml.cpp,pugixml.hpp、pugiconfig.hpp(在CSDN中可以下载到)三个文件分别添加到解决方案中 //XML文档如下 <?xml version="1.0"?> <Message> <Date>2013-11-6 15:57:33</Date> <Params> <paramname="proname" type="string" value="A" /> </Params> </Message> //添加头文件 #include “pugixml.hpp” //创建xml_document pugi::xml_document myDocument; //插入declaration pugi::xml_nodedecl=myDocument.append_child(pugi::node_declaration); decl.append_attribute("version")="1.0"; //并列插入Message节点 pugi::xml_nodeMessage=myDocument.append_child("Message"); //在Message节点下插入Date节点 pugi::xml_nodedate=Message.append_child("Date"); date.append_child(pugi::node_pcdata).set_value(prodata.time.c_str()); //在Message节点下插入Params节点 pugi::xml_nodeparams=Message.insert_child_after("Params",date); //在Params节点下插入param节点 pugi::xml_nodeparam1=params.append_child("param");; param1.append_attribute("name")="proname"; param1.append_attribute("type")="string"; param1.append_attribute("value")=prodata.proname.c_str(); //保存 myDocument.save_file(filepath); ////解析//// //加载XML myDocument.load_file(filepath); //解析两类节点 //第一类<Date>2013-11- 615:57:33</Date> pugi::xml_node Date=myDocument.child(“Message”).child(“Date”); Date.child_value()获取节点Date的text值 //第二类<paramname="proname" type="string" value="A" /> Pugi::xml_nodeparams=myDocument.chile(“Message”).child(“Params”); For(pugi::xml_nodeparam=params.first_child();param;param=param.next_sibling()) { String name=param.first_attribute().value(); If(name==”proname”) String value=param.last_attribute().value(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |