0

I am parsing an XML file using boost property tree of the following type:

<DocName>
    <InitCommands>
        <OptionalCommands>
            <command name="write" address="0x00000000"/>
            <command name="write" address="0x00000000"/>
            <command name="write" address="0x00000000"/>
        </OptionalCommands>
        <command name="write" address="0x00000000"/>
        <command name="write" address="0x00000000"/>        
    </InitCommands>
</DocName>

I would like to check if a certain element exists in the XML tree. Below is the code I am using:

namespace pt = boost::property_tree;
int main (){
   pt::ptree prop_tree;
   read_xml ("my.xml", prop_tree);
   pt::ptree::const_assoc_iterator it;
   it  = prop_tree.find("DocName.InitCommands.OptionalCommands");
   if (it != prop_tree.not_found())
     std::cout <<"Optional Options found !" << std::endl;              
}

However, running this code returns

it == prop_tree.not_found()

This works if I try to find the root element of my xml file i.e

it  = prop_tree.find("DocName");

Can someone please suggest how this find() function should be used ?

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
sbunny
  • 433
  • 6
  • 25

1 Answers1

0

Looking at the documentation of find()

assoc_iterator find(const key_type & key);
34. Find a child with the given key, or not_found() if there is none. There is no guarantee about which child is returned if multiple have the same key.

and get_child()

self_type & get_child(const path_type & path);
45. Get the child at the given path, or throw ptree_bad_path.

I would guess, that find is looking for immediate children -- this would explain why looking for the root element works --, and get_child is intended for going down a whole path.


So, either go step by step, e.g. something like

it = prop_tree.find("DocName");
it = it->find("InitCommands");
it = it->find("OptionalCommands");

or create a path_type and use get_child instead.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198