2

我是 C++ 新手,但我正在尝试定义一组标准的节点名称,然后映射到它们。

例如我的标准导入/输出模式是这样的:

<data>
<entry>
<id>1</id>
<description>Test</description>
</entry>
</data>

但是,有时我的 XML 导入会被命名为不同的名称,因此我想创建一个映射,以便它仍然以上述格式输出,即使输入文件具有以下命名约定:

<data>
<entry>
<id>1</id>
<content>Test</content>
</entry>
</data>

根据我所获得的文档和帮助,这段代码是我最好的猜测,但我一直在努力完成它:

#include "pugi/pugixml.hpp"

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

int main()
{

    // Define mappings, default left - map on the right
    const std::map<std::string, std::string> tagmaps
    {
          {"id", "id"}
        , {"description", "content"}
    };

    pugi::xml_document doca, docb;
    std::map<std::string, pugi::xml_node> mapa, mapb;

    for (auto& node: doca.child("data").children("entry")) {
        const char* id = node.child_value("id");
        mapa[id] = node;
    }

    for (auto& node: docb.child("data").children("entry")) {
        const char* idcs = node.child_value("id");
        if (!mapa.erase(idcs)) {
            mapb[idcs] = node;
        }
    }

    for (auto& eb: mapb) {
        // change node name if mapping found
        if((found = tagmaps.find(n.name())) != tagmaps.end()) {
            n.set_name(found->second.c_str());
        }

    }

}

理想情况下,此代码将允许以任何一种方式格式化 xml,但始终输出相同。任何帮助将非常感激。上面的代码给了我以下错误:

src/main.cpp:34:13: error: use of undeclared identifier 'found'
        if((found = tagmaps.find(n.name())) != tagmaps.end()) {
            ^
src/main.cpp:34:34: error: use of undeclared identifier 'n'
        if((found = tagmaps.find(n.name())) != tagmaps.end()) {
                                 ^
src/main.cpp:35:13: error: use of undeclared identifier 'n'
            n.set_name(found->second.c_str());
            ^
src/main.cpp:35:24: error: use of undeclared identifier 'found'
            n.set_name(found->second.c_str());
                       ^
4

1 回答 1

0

变量foundn从不声明。在该循环之前将这些变量声明为适当的类型,以便该部分代码如下所示:

编辑:稍微更改了代码,if 语句应在设置后检查 found 的值。

pugi::xml_node found, n;

for (auto& eb: mapb) {
    // change node name if mapping found
    found = tagmaps.find(n.name());
    if((found != tagmaps.end()) {
        n.set_name(found->second.c_str());
    }
}

另外,我认为n应该设置为循环内的特定节点(目前它没有价值)。考虑重命名n为其他名称,以明确该变量应包含的内容。

于 2015-04-19T12:46:14.477 回答