user7431005
user7431005

Reputation: 4539

boost::property_tree change order of elements

I use boost property tree to write some nice xml files and everything works fine... but I would like to somehow make sure that one specific block is at the start of the xml file. This block is a general block about the software and some general settings and it would be great for human readers that this block is at the beginning. Unfortunately I cannot make sure that this block is always the first that is written... Is there another easy solution or workaround?

Upvotes: 1

Views: 681

Answers (1)

sehe
sehe

Reputation: 393114

Just use insert:

ptree pt;

pt.add("a.c.d", "hello");
pt.add("a.e", "world");
pt.add("a.b", "bye");

write_xml(std::cout, pt, boost::property_tree::xml_writer_make_settings<std::string>(' ', 2));

Prints

<?xml version="1.0" encoding="utf-8"?>
<a>
  <c>
    <d>hello</d>
  </c>
  <e>world</e>
  <b>bye</b>
</a>

Using insert to insert a node at a specific location:

// let's move `b` to the start:
ptree pt;

pt.add("a.c.d", "hello");
pt.add("a.e", "world");
auto& a = pt.get_child("a");
a.insert(a.begin(), {"b", ptree{"bye"}});

write_xml(std::cout, pt, boost::property_tree::xml_writer_make_settings<std::string>(' ', 2));

Prints

<?xml version="1.0" encoding="utf-8"?>
<a>
  <b>bye</b>
  <c>
    <d>hello</d>
  </c>
  <e>world</e>
</a>

Upvotes: 1

Related Questions