我正在使用 Boost 的属性树来读取和写入 XML。使用我制作的电子表格应用程序,我想将电子表格的内容保存到 xml。这是一项学校作业,因此我需要使用以下 XML 格式:
<?xml version="1.0" encoding="UTF-8"?>
<spreadsheet>
<cell>
<name>A2</name>
<contents>adsf</contents>
</cell>
<cell>
<name>D6</name>
<contents>345</contents>
</cell>
<cell>
<name>D2</name>
<contents>=d6</contents>
</cell>
</spreadsheet>
对于一个简单的测试程序,我编写了:
int main(int argc, char const *argv[])
{
boost::property_tree::ptree pt;
pt.put("spreadsheet.cell.name", "a2");
pt.put("spreadsheet.cell.contents", "adsf");
write_xml("output.xml", pt);
boost::property_tree::ptree ptr;
read_xml("output.xml", ptr);
ptr.put("spreadsheet.cell.name", "d6");
ptr.put("spreadsheet.cell.contents", "345");
ptr.put("spreadsheet.cell.name", "d2");
ptr.put("spreadsheet.cell.contents", "=d6");
write_xml("output2.xml", ptr);
return 0;
}
基于此question https://stackoverflow.com/questions/15413022/how-to-create-xml-using-boost-property-tree我看到put
方法替换该节点上的任何内容,而不是添加新节点。这正是我所看到的功能:
输出.xml
<?xml version="1.0" encoding="utf-8"?>
<spreadsheet>
<cell>
<name>a2</name>
<contents>adsf</contents>
</cell>
</spreadsheet>
输出2.xml
<?xml version="1.0" encoding="utf-8"?>
<spreadsheet>
<cell>
<name>d2</name>
<contents>=d6</contents>
</cell>
</spreadsheet>
看着文档 http://www.boost.org/doc/libs/1_43_0/doc/html/boost/property_tree/basic_ptree.html#id906314-bb我看到这个add_child
方法将Add the node at the given path. Create any missing parents. If there already is a node at the path, add another one with the same key.
我不太明白如何使用它add_child
方法,有人能解释一下如何使用它吗?
有没有更好的方法来实现我想要的文件格式?