Search code examples
c++xmlparsingtreeboost-propertytree

Does boost::property_tree::xml_parser::read_xml preserve the order?


Considering the following xml element:

<elem>
    <sub_elem name="first">
    <sub_elem name="second">
</elem>

Concerning the property tree populated by boost::property_tree::xml_parser::read_xml, is it guaranteed that sub_elem "first" will be before sub_elem "second"?

The documentation states:

Reads XML from an input stream and translates it to property tree.

However it depends what "translates" means exactly.


Solution

  • From property tree documentation: https://www.boost.org/doc/libs/1_65_1/doc/html/property_tree/container.html I deduce that order of elements in XML file is preserved

    It is very important to remember that the property sequence is not ordered by the key. It preserves the order of insertion. It closely resembles a std::list. Fast access to children by name is provided via a separate lookup structure. Do not attempt to use algorithms that expect an ordered sequence (like binary_search) on a node's children.

    Looking at internal code in https://www.boost.org/doc/libs/1_51_0/boost/property_tree/detail/xml_parser_read_rapidxml.hpp one may see traversing over nodes and push_back calls. It should indeed work in simplest way of preserving order.