Pugixml C++ 解析布尔值

Pugixml C++ Parsing boolean

这是我的问题:

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"));

结果:

1
1

结果应该是1和0吧?但是在这两种情况下我总是得到 1。它只发生在 evaluate_boolean()。evaluate_number() 和 evaluate_string() 工作完美。

这是我的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;
}

您正在使用 XPath 将字符串 ("true") 转换为布尔值。如果字符串的长度不为零,则此 returns 为真。

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

您可以将字符串与 XPath 表达式中的 "true" 进行比较以修复该问题,或者使用 evaluate_node(*ptr).node().text().as_bool () 而不是 evaluate_boolean(*ptr).