我正在使用BOOST库在xml文件下面进行解析-
<da>
<m_day Type="int">15</m_day>
<m_month Type="int">8</m_month>
<m_year Type="int">1947</m_year>
</da>
我的cpp代码是:
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <iostream>
#include <fstream>
typedef struct date {
unsigned int m_day;
unsigned int m_month;
unsigned int m_year;
date( int d, int m, int y) : m_day(d), m_month(m), m_year(y)
{}
date() : m_day(1), m_month(1), m_year(2000)
{}
friend std::ostream& operator << (std::ostream& out, date& d)
{
out << "day: " << d.m_day
<< " month: " << d.m_month
<< " year: " << d.m_year;
return out;
}
template<class Archive>
void serialize(Archive& archive, const unsigned int version)
{
archive & BOOST_SERIALIZATION_NVP(m_day);
archive & BOOST_SERIALIZATION_NVP(m_month);
archive & BOOST_SERIALIZATION_NVP(m_year);
}
} date;
BOOST_CLASS_IMPLEMENTATION(date, boost::serialization::object_serializable);//object_serializable);
unsigned int flags = boost::archive::no_header;
int main()
{
std::ifstream file1("archive.xml");
boost::archive::xml_iarchive ia(file1,flags);
date dr;
ia >> BOOST_SERIALIZATION_NVP(dr);
std::ofstream file("archive2.xml");
boost::archive::xml_oarchive oa(file,flags);
// date da(15, 8, 1947);
oa & BOOST_SERIALIZATION_NVP(dr);
return 0;
}
我得到以下错误:
抛出'boost :: archive :: archive_exception'what()实例后终止调用:what():输入流错误中止(核心已转储)
对于不带属性的普通xml(如下所述),上述代码可以正常工作
<da>
<m_day>15</m_day>
<m_month>8</m_month>
<m_year>1947</m_year>
</da>
但是对于以前的xml文件,代码中是否有任何问题?您能否让我知道boost.i是否可行,我已经进行了很多搜索以找到答案,但没有得到任何答案。提前致谢 !!!
Boost序列化不是XML库。
Boost Archive xml_archive也不是XML库。
哎呀,甚至Boost属性树都不是XML库。
简而言之:Boost不包含XML库。
稍长一点:您可以使用Boost属性树来解析XML。它在后台使用RapidXML的派生类,您可以使用Boost属性树读取/写入相当通用的XML文档。
实际上,“属性树”界面非常具体,经常导致混乱。没有太多的控制权。
如果您关心XML支持(命名空间,空格,排序,PCDATA,处理指令,XPath,编码?...),请考虑使用XML库(在C ++中应使用哪种XML解析器?)
这是使用Boost属性树的方法
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
typedef struct date {
unsigned int m_day;
unsigned int m_month;
unsigned int m_year;
date( int d=1, int m=1, int y=2000) : m_day(d), m_month(m), m_year(y) {}
friend std::ostream& operator << (std::ostream& out, date& d) {
return out << "day: " << d.m_day << " month: " << d.m_month << " year: " << d.m_year;
}
void load(boost::property_tree::ptree const& pt)
{
m_day = pt.get("da.m_day", 1);
m_month = pt.get("da.m_month", 1);
m_year = pt.get("da.m_year", 2000);
}
} date;
#include <sstream>
int main() {
std::istringstream iss("<da>\n"
"<m_day Type=\"int\">15</m_day>\n"
"<m_month Type=\"int\">8</m_month>\n"
"<m_year Type=\"int\">1947</m_year>\n"
"</da>\n");
boost::property_tree::ptree pt;
read_xml(iss, pt);
date d;
d.load(pt);
std::cout << d << "\n";
}
印刷
day: 15 month: 8 year: 1947
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句