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 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:
#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;
}
}
add_executable(pugixml-example pugixml-example.cpp)
target_link_libraries(pugixml-example pugixml)
<?xml version="1.0" encoding="UTF-8"?>
<root-element>Test text</root-element>
Compile using:
cmake .
make