c++ - 使用 Boost property_tree 更新 XML 文件

标签 c++ xml boost boost-propertytree

我有以下 XML 文件:

<xml version="1.0" encoding="utf-8"?>
<Data>
    <Parameter1>1</Parameter1>
</Data>

我想添加一个新节点:Parameter2="2"到数据节点。此代码不起作用,保存的文件仍然只包含一个参数:

    boost::property_tree::ptree tree;
    boost::property_tree::ptree dataTree;

    read_xml("test.xml", tree);
    dataTree = tree.get_child("Data");
    dataTree.put("Parameter2", "2");

    boost::property_tree::xml_writer_settings w(' ', 4);
    write_xml("test.xml", tree, std::locale(), w);

如果我在 dataTree.put 之后添加这两行,我会得到正确的结果:

    tree.clear();
    tree.add_child("Data", dataTree);

我不喜欢这个解决方案,因为它会为更复杂的树结构带来问​​题。是否可以在不删除/添加子节点的情况下更新属性树?

最佳答案

您的代码几乎是正确的,这是更新子节点的正确方法。

但是,有一个小错误。当您输入时:

dataTree = tree.get_child("Data");

您将“ child ”的拷贝分配给 dataTree。因此,下一行是指拷贝而不是您的层次结构。你应该写:

boost::property_tree::ptree &dataTree = tree.get_child("Data");

因此您获得了对 child 的引用。

完整的例子是:

  using namespace boost::property_tree;
  ptree tree;

  read_xml("data.xml", tree);
  ptree &dataTree = tree.get_child("Data");
  dataTree.put("Parameter2", "2");

  xml_writer_settings<char> w(' ', 4);
  write_xml("test.xml", tree, std::locale(), w);

关于c++ - 使用 Boost property_tree 更新 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3299126/

相关文章:

c++ - 从需要多个输入的 C++ 源代码运行程序

Android elevation 和 setElevation 效果不一样

c++ - 关闭 MFC 对话框时的多线程对象销毁

iPhone核心数据问题: referenceData64 only defined for abstract class

c++ - Boost:以秒/毫/微/纳计算函数运行的时间

c++ - boost spirit : Why does phrase_parse behave differently to parse when parsing eol?

c++ - 将 Qt 集成到遗留 MFC 应用程序中

c++ - 在 QWebView 中隐藏滚动条时出现问题

c++ - 铿锵++ : error: linker command failed with exit code 1 (use -v to see invocation) in cpp with ffmpeg

php - DomDocument 解析换行符适用于 span 但不适用于 img