【问题标题】:How to correctly access xml attributes using pugixml?如何使用 pugixml 正确访问 xml 属性?
【发布时间】:2020-01-01 03:43:17
【问题描述】:

我是 xml 新手,使用 pugixml 文档我无法将节点属性读取到控制台。问题的核心是我不明白节点访问结构是如何工作的,我也无法使用我的代码弄清楚。

提供的代码是实际 pugixml 手册中稍作修改的行,所以我不确定它为什么不起作用。

已加载 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<settings description="settings root description">
  <!--settings for the options menu-->
  <options description="game options">
    <resolution description="resolution in 16:9 ratio">6</resolution>
    <volume description="volume setting">0</volume>
  </options>
</settings>

C++ 代码尝试使用 XML 文件

//set up and load settings xml doc
pugi::xml_document settingsXML;
pugi::xml_parse_result settingsResult = settingsXML.load_file("SFMLVania/include/Settings.xml");

std::cout << "Root description: " << settingsXML.root().attribute("description").as_string();

我希望看到: “根描述:设置根描述” 在控制台中。

相反,我得到: "根描述:"

第二次尝试——尝试获取任何数据并找出我在树中的位置:

std::cout << "Second attempt: " << settingsXML.first_attribute().as_string();

我从第二次尝试中得到的只是控制台吐出:“第二次尝试:”

【问题讨论】:

    标签: c++ xml xml-attribute pugixml


    【解决方案1】:

    事实证明,我的加载路径不存在,我忘记使用 ../ 进入一个目录,然后从存储 .exe 的 Debug 文件夹中退出。我通过测试可以作为布尔值传递的加载结果来解决这个问题。

    if (settingsResult)
        {
            std::cout << "returned true\n";
        }
        else
            std::cout << "returned false\n";
        if (!settingsResult)
        {
            std::cout << "also returned false\n";
        }
    

    我包含了一些多余的返回值,以防 bool 值没有按预期运行。

    结果显示没有加载文件(它返回false),当我重新检查我的文件结构并将../作为测试添加到文件路径时,它返回true。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      相关资源
      最近更新 更多