在 pugixml 中一般从 xpath_node_set 中提取内容

Extracting content from xpath_node_set generically in pugixml

现在我正在使用 pugixml 执行此 xpath 查询:

"//a/@href"

使用以下代码:

std::vector<std::string> web::parser::query(std::string xpath)
{
    pugi::xpath_node_set links = document.select_nodes(xpath.c_str());
    std::cout << "OK" << std::endl;

    std::vector<std::string> urls;
    for (auto link : links)
        urls.push_back(link.attribute().value());

    return urls;
}

注意我需要指定我查询的是一个属性,因为我调用 link.attribute().value()) 而不是 link.node().value()).

有没有办法让这个 query 函数在两种情况下(属性和 PCData)都起作用?

查阅了pugixml的参考手册,发现xpath_nodexml_nodexml_attribute的并集。

这意味着其中之一为空或两者均为空。有了这些信息,我可以解决这个问题:

std::vector<std::string> web::parser::query(std::string xpath)
{
    pugi::xpath_node_set node_set = document.select_nodes(xpath.c_str());

    std::vector<std::string> result;
    for (auto xpath_node : node_set) {
        if (xpath_node.attribute() != nullptr)
            result.push_back(xpath_node.attribute().value());
        else
            result.push_back(xpath_node.node().child_value());
    }

    return result;
}

这在我的测试用例中似乎是正确的。