Search code examples
c++boostboost-propertytree

Boost Property Tree and Xml parsing Problems


I'm using boost::property_tree. The documentation is very vague and overall unhelpful for the most part. Looking at the source/examples didn't help that much, either.

What I'm wondering is the following:

<VGHL>
    <StringTable>
        <Language>EN</Language>
        <DataPath>..\\Data\\Resources\\Strings\\stringtable.bst</DataPath>
    </StringTable>
</VGHL>

How can I iterate over all the elements at the current level? If I do this:

read_xml(fin, bifPropTree);
VGHL::String tablePath;
BOOST_FOREACH(boost::property_tree::wiptree::value_type &v, 
              bifPropTree.get_child(L"VGHL.StringTable"))
{
    m_StringTable->ParseEntry(v.second, tablePath);
}

In ParseEntry I try this:

VGHL::String langName = stringTree.get<VGHL::String>(L"StringTable.Language");

Results in an exception (not doesn't exist). I've also tried this:

VGHL::String langName = stringTree.get<VGHL::String>(L"Language");

Same problem.

From my understanding when I call ParseEntry I am passing a reference to the tree at that node.

Is there any way to deal with this, when I have multiple entries of StringTable using property tree?


Solution

  • ParseEntry receives a reference to each of the children nodes of the current level. So, you cannot ask the values using the node name, because you already have a child node. The node name is stored in v.first.

    You can iterate over all the elements at a given level using get_child to select the level and then BOOST_FOREACH to iterate. Each iterator will be a pair representing the name of the node and the node data:

    using boost::property_tree::wiptree;
    
    wiptree &iterationLevel = bifPropTree.get_child(L"VGHL.StringTable");
    BOOST_FOREACH(wiptree::value_type &v, iterationLevel)
    {   
      wstring name = v.first;
      wstring value = v.second.get<wstring>(L"");
      wcout << L"Name: " << name << L", Value: " << value.c_str() << endl;
    }
    

    This code would print:

    Name: Language, Value: EN

    Name: DataPath, Value: ..\\Data\\Resources\\Strings\\stringtable.bst

    If you do not want to iterate, you can select the node level and then look for the nodes using their name:

    wiptree &iterationLevel = bifPropTree.get_child(L"VGHL.StringTable");
    wstring valueLang = iterationLevel.get<wstring>(L"Language");
    wstring valuePath = iterationLevel.get<wstring>(L"DataPath");
    wcout << valueLang << endl << valuePath << endl;
    

    This code would print:

    EN

    ..\\Data\\Resources\\Strings\\stringtable.bst