Boost.PropertyTree是生成XML的好方法 - 尤其是在您已经使用Boost的情况下。
下面是一个完整的示例程序:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
using boost::property_tree::ptree;
using boost::property_tree::write_xml;
using boost::property_tree::xml_writer_settings;
int wmain(int argc, wchar_t* argv[]) {
char* titles[] = {"And Then There Were None", "Android Games", "The Lord of the Rings"};
ptree tree;
tree.add("library.<xmlattr>.version", "1.0");
for (int i = 0; i < 3; i++) {
ptree& book = tree.add("library.books.book", "");
book.add("title", titles[i]);
book.add("<xmlattr>.id", i);
book.add("pageCount", (i+1) * 234);
}
// Note that starting with Boost 1.56, the template argument must be std::string
// instead of char
write_xml("C:\\Users\\Daniel\\Desktop\\test.xml", tree,
std::locale(),
xml_writer_settings<char>(' ', 4));
return 0;
}
生成的XML看起来是这样的:
这是特别好的
<?xml version="1.0" encoding="utf-8"?>
<library version="1.0">
<books>
<book id="0">
<title>And Then There Were None</title>
<pageCount>234</pageCount>
</book>
<book id="1">
<title>Android Games</title>
<pageCount>468</pageCount>
</book>
<book id="2">
<title>The Lord of the Rings</title>
<pageCount>702</pageCount>
</book>
</books>
</library>
一件事是用点分隔的路径,让您隐式创建沿途的所有节点。 documentation是相当微薄,但与ptree.hpp
一起应该给你一个它的工作原理。
我已经使用[libxml ++](http://libxmlplusplus.sourceforge.net/)来生成XML,但我不能保证它是最简单的方法! :-) – 2008-11-19 21:10:53