I've been developing a simple console application in C++ using the TinyXML2 library, and I honestly can't help but feel what I'm doing is not very robust. Maybe that's just the nature of parsing XML (this is my first foray into the topic, so I've no idea.)
The following code works to the best of my knowledge, but it feels like there has to be a better way than manually navigating to each element, checking for null pointers, then grabbing the information. Is there a more elegant way to handle this? I have to be missing something within the documentation, because I feel like I'm writing a lot of redundant code here.
#include <iostream>
#include "tinyxml2.h"
int main() {
tinyxml2::XMLDocument document;
if (document.LoadFile("games.xml") == tinyxml2::XML_SUCCESS) {
std::cout << "'games.xml' successfully loaded." << std::endl;
tinyxml2::XMLElement *root = document.RootElement();
std::cout << root->Value() << std::endl;
tinyxml2::XMLElement *child;
for (child = root->FirstChildElement(); child != nullptr; child = child->NextSiblingElement()) {
std::cout << "\t" << child->Value() << std::endl;
if (child->FirstChildElement("name") == nullptr) {
std::cerr << "Error: null pointer." << std::endl;
return 1;
}
if (child->FirstChildElement("system") == nullptr) {
std::cerr << "Error: null pointer." << std::endl;
return 1;
}
if (child->FirstChildElement("status") == nullptr) {
std::cerr << "Error: null pointer." << std::endl;
return 1;
}
const char* game_name = child->FirstChildElement("name")->GetText();
const char* game_system = child->FirstChildElement("system")->GetText();
const char* game_status = child->FirstChildElement("status")->GetText();
if (game_name == nullptr || game_system == nullptr || game_status == nullptr) {
std::cout << "Error: null pointer." << std::endl;
return 1;
}
std::cout << "\t\t" << game_name << std::endl;
std::cout << "\t\t" << game_system << std::endl;
std::cout << "\t\t" << game_status << std::endl;
}
} else {
std::cerr << "Unable to load 'games.xml'. Error code: " << document.ErrorID() << std::endl;
return 1;
}
return 0;
}