c++xmlfiletinyxml2

How to read XML element using tinyxml2 in C++?


I am trying to read config.xml with following simple content:

<?xml version="1.0" encoding="utf-8"?>
<config>
    <languages>
        <language>cs</language>
        <language>en</language>
    </languages>
    <databases>
        <database>
            <domain>localhost</domain>
            <server>localhost</server>
            <username>admin</username>
            <password>admin</password>
            <name>annmproject</name>
            <prefix>site_</prefix>
        </database>
    </databases>
</config>

I wrote some very simple code for reading first language:

config->LoadFile("config.xml");

if(config->ErrorID() != 0)
    return 1;

tinyxml2::XMLElement* root = config->FirstChildElement("config");
tinyxml2::XMLElement* element = root->FirstChildElement("languages");
std::cout << element->FirstChildElement("language")->GetText() << "<br>" << endl;

It should work fine. The file is successfuly opened. And when I am testing null pointers, everything is alright. But when I try to print the value, it stops to work.


Solution

  • Did you make tinyxml2::XMLDocument* config; a pointer? Because you write config->LoadFile("config.xml");.

    Try with an easier definition of config like so:

    tinyxml2::XMLDocument config;
    config.LoadFile("config.xml");
    

    Can't say for sure what is wrong if no error message is present, but you're missing the std:: before endl. Code update for config as a value instead of a pointer:

    tinyxml2::XMLElement* root = config.FirstChildElement("config");
    tinyxml2::XMLElement* element = root->FirstChildElement("languages");
    
    std::cout << element->FirstChildElement("language")->GetText() << std::endl;
    

    Option 2 with iterating (config as a value):

    tinyxml2::XMLElement* root = config.FirstChildElement("config");
    tinyxml2::XMLElement* element = root->FirstChildElement("languages");
    
    for (tinyxml2::XMLElement* language = element->FirstChildElement(); language != NULL; language = language->NextSiblingElement())
    {
        std::cout << language->GetText() << std::endl;
    }
    

    EDIT: Note where I use the dots "." and where the arrows "->"!