7

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?

1 Answer 1

10

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Very helpful, and now I don't need to ask in very unfriendly Boost users forum :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.