这几天公司需要,研究了下Xml的使用。
由于某些原因我们不能直接使用文件,于是网上很多教程就作废了。而且官方也没有相关例子,很难受。最后,研究了下源文件,终于知道了原理
不废话了,先上代码。
string类型到Poco::Document指针的转化
#include <Poco/DOM/DOMParser.h>
#include <Poco/DOM/Document.h>
#include <Poco/DOM/AutoPtr.h>
//xml文件中内容
std::string XHTML = "<root><a><aa>111</aa><ab>222</ab></a><b>2</b></root>";
//转化
Poco::XML::DOMParser parser;
parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACE_PREFIXES, false);
Poco::XML::AutoPtr<Poco::XML::Document> pDoc = parser.parseString(XHTML);
Poco::Document指针到string类型的转化
#include <Poco/DOM/DOMWriter.h>
#include <sstream>
//使用string输出流
std::ostringstream ostr;
Poco::XML::DOMWriter writer;
writer.writeNode(ostr, pDoc);
std::string xml = ostr.str();
然后是对Document的操作
#include <Poco/DOM/Document.h>
#include <Poco/DOM/AutoPtr.h>
std::string node1 = pDoc->getNodeByPath("/root/a/aa")->firstChild()->getNodeValue();
std::string node2 = pDoc->getNodeByPath("/root/b")->firstChild()->getNodeValue();
std::string node3 = pDoc->getNodeByPath("/root/a/ab")->firstChild()->getNodeValue();
pDoc->getNodeByPath("/root/a/ab")->firstChild()->setNodeValue("123123");
需要注意的是,Document指针里面的getNodeByPath函数,返回的Node指针是引用Document指针指向的内容。如果你把Node指针直接设为AutoPtr的智能指针的时候,它会把自己指向的Node释放。所以,除了Document的指针,其他Node,Attr什么的千万别用智能指针。我花了半天才查出这个bug,惨痛的教训!