使用 Boost property_tree 更新 XML 文件

发布于 2024-09-10 10:53:23 字数 696 浏览 5 评论 0原文

我有以下 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);

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

I have the following XML file:

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

I want to add a new node: Parameter2="2" to the Data node. This code doesn't work, saved file still contains only one parameter:

    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);

If I add these two lines after dataTree.put, I get correct result:

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

I don't like this solution, because it creates problems with more complicated tree structutes. Is it possible to update property tree without deleting/adding child nodes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2024-09-17 10:53:23

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

然而,有一个小错误。当您键入时:

dataTree = tree.get_child("Data");

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

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

这样你就获得了对孩子的引用。

完整的例子是:

  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);

Your code is almost right, that is the right way to update a child node.

However, there is a small bug. When you type:

dataTree = tree.get_child("Data");

You assign to dataTree a copy of the "child". So, the next line refers to the copy and not to your hierarchy. You should write:

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

So you obtain a reference to the child.

The complete example is:

  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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文