c++ - 从 'mapped_type' 没有可行的转换

标签 c++ xml c++11 xml-parsing

这是我比较 XML 文件的代码,使用映射将 xml 标签名称定义为内容。

#include "pugi/pugixml.hpp"

#include <iostream>
#include <string>
#include <map>

using namespace std;

int main()
{
    pugi::xml_document doca, docb;
    std::map<std::string, pugi::xml_node> mapa, mapb;
    std::map<int, std::string> tagMap {make_pair(1, "data"), make_pair(2, "entry"), make_pair(3, "id"), make_pair(4, "content")};

    if (!doca.load_file("a.xml") || !docb.load_file("b.xml")) {
        std::cout << "Can't find input files";
        return 1;
    }

    for (auto& node: doca.child(tagMap[1]).children(tagMap[2])) {
        auto id = node.child_value(tagMap[3]);
        mapa[id] = node;
    }

    for (auto& node: docb.child(tagMap[1]).children(tagMap[2])) {
        auto idcs = node.child_value(tagMap[3]);
        if (!mapa.erase(idcs)) {
            mapb[idcs] = node;
        }
    }
}

我得到的错误是这样的:

src/main.cpp:20:30: error: no viable conversion from 'mapped_type' (aka 'std::__1::basic_string<char>') to
      'const char_t *' (aka 'const char *')
        for (auto& node: doca.child(tagMap[1]).children(tagMap[2])) {
                                    ^~~~~~~~~

根据推荐,我尝试了这种方法:

        auto id = node.child_value(tagMap[3].c_str());

但我仍然得到同样的错误。似乎我试图使用 map 来定义标签名称已经导致了很多问题,而不仅仅是对它进行硬编码,但是映射它似乎是合乎逻辑的,因为将来我会将 map 移动到外部文件,这样我就可以为不同的程序运行程序XML 标签无需每次都重新编译。

最佳答案

如果你仔细阅读错误

src/main.cpp:20:30: error: no viable conversion from 'mapped_type' (aka 'std::__1::basic_string<char>') to
  'const char_t *' (aka 'const char *')
    for (auto& node: doca.child(tagMap[1]).children(tagMap[2])) {
                                ^~~~~~~~~

您会看到您正在将 std::string 传递给需要 const char* 的对象。具体来说:

doca.child(tagMap[1])

tagMap[1] 是一个 std::stringchild() 需要一个 const char* .所以:

for (auto& node: doca.child(tagMap[1].c_str()).children(tagMap[2].c_str())) {

关于c++ - 从 'mapped_type' 没有可行的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29806337/

相关文章:

c++ - 如何在 C/C++ 中填充结构填充?

java - 以指针为参数的 C++ 函数并使用 swig 接口(interface)处理它

c++ - 前向声明继承信息

c++ - 如何正确使用BOOST_THROW_EXCEPTION?

c++ - 线程矩阵乘法

c++ - 根据 if 语句初始化对象

java - 你如何在 Android 的 arrayList 中的文本旁边添加图像?

iphone - 如何在 iPhone 中解析 gdata xml?

java - 使用 Java 进行离线 XML 验证

c++ - 使用 operator[] 和 operator int() 的模糊重载