Updating XML file using Boost property_tree

Alex F picture Alex F · Jul 21, 2010 · Viewed 9k times · Source

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?

Answer

J. Calleja picture J. Calleja · Jul 21, 2010

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