Home > Blockchain >  Why is the data parsed by pugixml lost in another function?
Why is the data parsed by pugixml lost in another function?

Time:12-08

I have 2 functions:

void XMLParser::ParseScene(const char* path)
{
    // Load the XML file
    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load_file(path);

    scene = doc.child("scene");
}

and

void XMLParser::CreateModelLights(pugi::xml_node node)
{
    GLuint i = 0;
    for (pugi::xml_node entity : node.children())
    {
        [...]
    }
}

I am calling parser.ParseScene("src/xml/scene.xml"); to generate parser.scene and then call parser.CreateModelLights(parser.scene);, but it gives me rubbish data in node parameter / parser.scene.

If I put scene = doc.child("scene"); on CreateModelLight() first line it will parse my data ok in parser.scene, but I don't want to force the node like that because I am calling the function recursively. Ideally I want to parse my XML in ParseScene() and then store it a pugi::xml_node variable declared in the header that I can use in functions like CreateModelLights().

XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<scene>
    [...]
</scene>

Rubbish data I get: bad data

Data I should get: good data

CodePudding user response:

This is not terribly clear in the documentation, but PugiXML uses a fairly common memory management pattern: The pugi::xml_document owns the entire XML DOM tree, and pugi::xml_node objects are just shallow pointers into this tree.

This means that you need to keep the pugi::xml_document object alive for as long as there are pugi::xml_node objects pointing into it. Probably the quickest way is to promote doc to a member variable.

  • Related