【问题标题】:Use pugiXML to rename nodes based on a std::map使用 pugiXML 根据 std::map 重命名节点
【发布时间】:2015-06-26 01:35:58
【问题描述】:

我是 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());
                       ^

【问题讨论】:

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


【解决方案1】:

从未声明变量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 重命名为其他名称,以明确该变量应包含的内容。

【讨论】:

  • 感谢您的回复。在这种情况下,我收到此错误src/main.cpp:49:19: error: no viable overloaded '=' if((found = tagMap.find(n.name())) != tagMap.end()) {,您知道是什么原因造成的吗?
  • 查看我的编辑,我认为应该可以解决该错误。 found需要在if条件之前设置
  • @Kvothe 不,您不能将map::const_iterator 分配给xml_node
  • @Barry 哦,是的,现在再看一遍 - 我稍后会修改(我现在必须回去工作),或者如果你现在有时间自己修改
猜你喜欢
  • 2021-05-17
  • 2018-11-23
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 2019-09-27
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多