C++ Poco库 Xml使用

本文介绍了如何使用Poco库进行XML字符串与Document对象之间的转换,并提供了具体的代码示例。此外,还分享了从Document对象中读取节点值及修改节点值的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几天公司需要,研究了下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,惨痛的教训!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值