vs2010环境开发
注意:
编译时要记得添加静态库路径,以及包含的头文件路径。如果要直接跑程序,需要将涉及的静态库的动态库版本放置到程序所在的路径下。以便程序自己可以找到。
#include "Poco/DOM/Text.h"
#include "Poco/DOM/Element.h"
#include "Poco/DOM/Comment.h"
#include "Poco/DOM/ProcessingInstruction.h"
#include "Poco/DOM/Attr.h"
#include "Poco/DOM/Document.h"
#include "Poco/AutoPtr.h"
#include "Poco/DOM/DOMWriter.h"
#include "Poco/XML/XMLWriter.h"
#include "Poco/FileStream.h"
#include "Poco/Util/XMLConfiguration.h" using Poco::Util::XMLConfiguration;
using Poco::AutoPtr;
#pragma comment(lib,"PocoFoundation.lib")
#pragma comment(lib,"PocoXML.lib")
#pragma comment(lib,"PocoUtil.lib")xml文件的生成代码
AutoPtr<Poco::XML::Document> pDoc = new Poco::XML::Document;
AutoPtr<Poco::XML::Element> myRoot = pDoc->createElement("Root");
AutoPtr<Poco::XML::Element> myChild = pDoc->createElement("Child");
AutoPtr<Poco::XML::Element> myGrandChild = pDoc->createElement("GrandChild");
AutoPtr<Poco::XML::Text> nameNode = pDoc->createTextNode("my_name_is_xiaoqiang");
AutoPtr<Poco::XML::ProcessingInstruction> pi = pDoc->createProcessingInstruction("xml","version='1.0' encoding='UTF-8'" );
AutoPtr<Poco::XML::Comment> comm = pDoc->createComment("new_day");
myGrandChild->appendChild(nameNode);
myChild->appendChild(myGrandChild);
myRoot->appendChild(myChild);
pDoc->appendChild(pi);
pDoc->appendChild(comm);
pDoc->appendChild(myRoot);
Poco::XML::DOMWriter write;
write.setOptions(Poco::XML::XMLWriter::PRETTY_PRINT);
Poco::FileStream ofs("./example.xml",std::ios::in);
write.writeNode(ofs,pDoc);xml文件的读取
要注意:读取文件时如果找不到对应的Key值,Poco内部会抛出异常直接崩溃。推荐捕获异常,然后返回false之类的才好。
AutoPtr<XMLConfiguration> pConfig(new XMLConfiguration("./example.xml"));
//std::string prop1 = pConfig->getString("prop1");
//int prop2 = pConfig->getInt("prop2");
//std::string prop3 = pConfig->getString("prop3");
//
//std::string prop4 = pConfig->getString("prop3.prop4");
//prop4 = pConfig->getString("prop3.prop4[@attr]");
//prop4 = pConfig->getString("prop3.prop4[1][@attr]");
std::string prop1 = pConfig->getString("Child.GrandChild");
int i=0;
//int prop2 = pConfig->getInt("prop2");
//std::string prop3 = pConfig->getString("prop3");
//
//std::string prop4 = pConfig->getString("prop3.prop4");
//prop4 = pConfig->getString("prop3.prop4[@attr]");
//prop4 = pConfig->getString("prop3.prop4[1][@attr]"); 最好要捕获下异常,防止程序崩溃
std::string prop1;
try{
prop1 = pConfig->getString("Child.GrandChilds");
}catch(...)
{
}附录:
<config>
<prop1>value1</prop1>
<prop2>123</prop2>
<prop3>
<prop4 attr="value3" />
<prop4 attr="value4" />
</prop3>
</config>
<?xml version='1.0' encoding='UTF-8'?>
<!--new_day-->
<Root>
<Child>
<GrandChild>my_name_is_xiaoqiang</GrandChild>
</Child>
</Root>
在VS2010环境下,利用Poco库进行XML文件的生成和解析。开发时需注意配置静态库路径和头文件路径。运行时确保动态库文件与程序在同一路径。Poco库在读取XML时,若找不到键值会抛出异常导致程序崩溃,建议进行异常捕获以避免程序异常终止。

2345

被折叠的 条评论
为什么被折叠?



