【问题标题】:how to create xml using boost property_tree如何使用 boost property_tree 创建 xml
【发布时间】:2013-03-03 00:33:40
【问题描述】:

我需要为我的输出创建 xml。 我有一个索引名称列表。 我想以一种格式将其填充到 xml 文件中。

那是

<response>
      <indexes>
          <index>abc</index>
          <index>xyz</index>
          <index>pqr</index>
      </indexes>
</response>

我的向量 index_list 中有该列表。

谁能帮帮我。

我已经为此尝试了一些代码。 接下来是

boost::property_tree::ptree tree;
stringstream output;
for (std::vector<string>::const_iterator it = index_list.begin();
        it != index_list.end(); it++) {
    std::cout << *it << "\n";
    tree.put("response.indexes.index", *it);
}
if (format == "xml") {
    write_xml(output, tree);
} else {
    write_json(output, tree);
}

当我运行上面的代码时。我只得到列表中的姓氏。那就是

<response>
  <indexes>
      <index>pqr</index>
  </indexes>
</response>

【问题讨论】:

  • This 有效。我对这个库没有任何经验,所以我不知道这是否是最好的方法。
  • 谢谢llonesmiz..你的做法也不错..印象深刻。

标签: c++ boost xml-parsing


【解决方案1】:

put 方法将删除任何现有值,请参阅之前相关的问题here

您必须为列表中的每个条目使用不同的键,以避免数据丢失。

Boost docs

调用 put 会在指定路径插入一个新值,这样调用 获取指定相同的路径将检索它。

【讨论】:

  • 感谢您的信息。如果我使用 put 我无法获得像 这样的 xml .. 我会尝试 add()..
  • 我的印象是这是propertytree的一个特性。 XML 只是用来表示数据结构,所以不要指望用 PTree 做所有在 XML 中可以做的事情。
猜你喜欢
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2023-03-07
  • 2012-12-13
相关资源
最近更新 更多