Search code examples
c++pugixml

Pugixml C++ Parsing boolean


Here is my problem:

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<server>
    <a>true</a>
    <b>false</b>
</server>

test.cpp

sampgdk::logprintf("%d", config.get<bool>("server/a"));
sampgdk::logprintf("%d", config.get<bool>("server/b"));

result:

1
1

The result should be 1 and 0 right? But I always get 1 in both instances. It only happens to evaluate_boolean().evaluate_number() and evaluate_string() are working perfectly.

Here is my config.get

template<> bool framework::xml::get(std::string xpath) {
if (is_open) {
    try {
        return pugi::xpath_query(xpath.data()).evaluate_boolean(*ptr);
    }
    catch (std::exception &e) {
        sampgdk::logprintf("XML exception: %s\n", e.what());
    }
}
    return false;
}

Solution

  • You are converting a string ("true") to a boolean using XPath. This returns true iff the length of the string is non-zero.

    http://www.w3.org/TR/xpath/#section-Boolean-Functions

    You can compare the string to "true" in the XPath expression to fix that, or to use evaluate_node(*ptr).node().text().as_bool() instead of evaluate_boolean(*ptr).