How to check if XML element exists in PugiXML

Checking if an element exists in PugiXML is simple: Just call bool(element) or use the element directly inside an if clause:

example.cpp
// Example on using bool(element)
cout << "<root-element> exists: " << std::boolalpha
     << bool(doc.child("root-element")) << endl;
cout << "<not-root-element> exists: " << std::boolalpha
     << bool(doc.child("not-root-element")) << endl;

// Example on using the element directly inside an if clause
if(doc.child("root-element")) {
    cout << "Yes, <root-element> exists!" << endl;
}

Full example:

example.cpp
#include <iostream>
#include <pugixml.hpp>
using namespace std;
using namespace pugi;

int main() {
    xml_document doc;
    xml_parse_result result = doc.load_file("test.xml");

    // Example on using bool(element)
    cout << "<root-element> exists: " << std::boolalpha
         << bool(doc.child("root-element")) << endl;
    cout << "<not-root-element> exists: " << std::boolalpha
         << bool(doc.child("not-root-element")) << endl;

    // Example on using the element directly inside an if clause
    if(doc.child("root-element")) {
        cout << "Yes, <root-element> exists!" << endl;
    }
}
example.txt
add_executable(pugixml-example pugixml-example.cpp)
target_link_libraries(pugixml-example pugixml)
example.xml
<?xml version="1.0" encoding="UTF-8"?>
<root-element>Test text</root-element>

Compile using:

example.sh
cmake .
make

Check out similar posts by category: C/C++