lundi 17 janvier 2022

How traverse an xml file and make a composite object at the end?

I have a simple xml file:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Menu name="First Menu" caption="FirstMenu">
    <Menu name="Do Fancy Stuff" caption="DoFancyStuff">
        <Menu name="Exit" caption="Exit">
            <Menu name="Run away" caption="RunAway"/>
            <Menu name="Foo" caption="Foo"/>
        </Menu>
    </Menu>
    <Menu name="Bar" caption="Bar"/>
    <Menu name="Tar" caption="Tar"/>
    <Menu name="Zar" caption="Zar">
        <Menu name="Ghar" caption="Ghar"/>
        <Menu name="Ghar" caption="Ghar"/>
    </Menu>
    <Menu name="Kar" caption="Kar"/>
    <Menu name="Far" caption="Far"/>
</Menu>

And i want parse it and make a composite object at the end. this is my attempt so far: https://gist.github.com/LinArcX/37eea86b43a9b2d1e6302ed2219a12fb

All the code works. The only part that remained unsolved for me is: traverseXmlReturnCompsiteObject function. Because i don't know how can i create objects on the fly for each Leaf/Composite object. Another concern is that i don't know how can i keep the fathers(for the next recursion) to add their children to it.

The output of traverseXmlReturnCompsiteObject should be a composite object that contains all the internal objects.

Any idea?

Thanks in advance.

Edit: If there was no xml parsing and recursion, creating composite object was as simple as below code:

std::shared_ptr<Component> TREE;
TREE = std::shared_ptr<Component>(new Composite("TREE"));

std::shared_ptr<Component> B1(new Composite("B1"));
std::shared_ptr<Component> L1(new Composite("L1"));
std::shared_ptr<Component> L2(new Composite("L2"));
std::shared_ptr<Component> L3(new Composite("L3"));

B1->add(L1);
B1->add(L2);
B1->add(L3);

std::shared_ptr<Component> B2(new Composite("B2"));
std::shared_ptr<Component> L4(new Composite("L4"));
std::shared_ptr<Component> L5(new Composite("L5"));

B2->add(L4);
B2->add(L5);

TREE->add(B1);
TREE->add(B2);

Aucun commentaire:

Enregistrer un commentaire