c++ - 使用 RapidXML 解析 XML 文件 - 仅解析文件的第一行

标签 c++ xml parsing rapidxml

我在使用 RapidXML 时遇到问题,只能解析我文件的第一行(或者看起来如此)。当我输入示例文件时,它仅获取第一个节点(“map”),没有其他任何内容。解析后我在 Xcode 中设置了一个断点以检查结果,大多数属性似乎都为 NULL 值。有没有人对如何解决这个问题有任何建议?据我了解,解析器应该会产生某种形式的树状结构。也许我对结果数据结构有误解?

这是我的用法:

#include <iostream>
#include "rapidxml_utils.hpp"

using namespace std;

int main(){
    rapidxml::file<> xmlFile("sample.txt.xml");
    rapidxml::xml_document<> doc;
    doc.parse<0>(xmlFile.data());

    cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
    rapidxml::xml_node<> *node = doc.first_node("map");
    cout << "Node map has value " << node->value() << "\n";
    for (rapidxml::xml_attribute<> *attr = node->first_attribute();
         attr; attr = attr->next_attribute())
    {
        cout << "Node foobar has attribute " << attr->name() << " ";
        cout << "with value " << attr->value() << "\n";
    }
}

这是我尝试解析的文件示例:

<?xml version="1.0" encoding="utf-8"?>
<map>
  <room>
    <name>Entrance</name>
    <description>You find yourself at the mouth of a cave</description>
    <item>torch</item>
    <trigger>
      <type>permanent</type>
      <command>n</command>
      <condition>
        <has>no</has>
        <object>torch</object>
        <owner>inventory</owner>
      </condition>
      <print>*stumble* need some light...</print>
    </trigger>
    <border>
      <direction>north</direction>
      <name>MainCavern</name>
    </border>
  </room>
</map>

最佳答案

您混淆了 XML 属性元素

属性看起来像这样:<map name="Zork" author="Infocom">

如果您想遍历“树”中的所有元素,您确实需要一个使用 rapidxml first_node() 的递归算法。和 next_sibling()方法。

关于c++ - 使用 RapidXML 解析 XML 文件 - 仅解析文件的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847272/

相关文章:

c - 在C语言中将IP地址截断为/24的最简单方法是什么?

c++ - 段错误进程 ID 和核心转储进程 ID 不同。为什么?

C++构造函数调用

c++ - 使用 SFINAE 根据类模板参数的类型更改类中调用的函数

java - 如何从字符串数组列表中随机选择

java - jaxb 的 XML 解析问题

java - 在 Java 反射中将 int 转换为 Enum

c++ - 无法声明包含类型的对象

java dom 转义字符

arrays - 希望将 EMV 数据解析为 TLV