曾经写过一篇"使用Boost property tree来解析带attribute的xml", 但是还有姐妹篇一直没贴。看看前一篇贴了都快都快3年了,时间过的真快。

这一小篇就算是下篇吧。即用boost::property_tree生成带attribute的xml。

直接看demo code:

#include <iostream>
#include <sstream>
#include <boost/property_tree/xml_parser.hpp> using namespace std; int main(){
using boost::property_tree::ptree;
ptree pt; ptree tab1;
ptree tab2; tab1.put("attr1", "value1");
tab1.put("attr1.<xmlattr>.code", "ABC");
tab1.put("attr2", "value2"); tab2.put("attr3", "value3");
tab2.put("attr3.<xmlattr>.code", "XYZ"); ptree array;
auto& a = array.add_child("table1", tab1);
a.put("<xmlattr>.tabid", "1"); auto& b = array.add_child("table2", tab2);
b.put("<xmlattr>.tabid", "2"); pt.put_child("demoxml", array); ostringstream oss; write_xml(oss, pt, xml_writer_settings<char>(' ', 2)); cout << oss.str() << endl; return 0;
}

生成的xml例如以下:

<?xml version="1.0" encoding="utf-8"?>
<demoxml>
<table1 tabid="1">
<attr1 code="ABC">value1</attr1>
<attr2>value2</attr2>
</table1>
<table2 tabid="2">
<attr3 code="XYZ">value3</attr3>
</table2>
</demoxml>

。。!欢迎转载,请注明本文链接:http://blog.csdn.net/mosaic/article/details/39047327 !!!

!!

05-11 09:37