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

时间:2015-11-21 18:52:53

标签: 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>

1 个答案:

答案 0 :(得分:1)

您会混淆XML 属性元素

属性如下所示:<map name="Zork" author="Infocom">

如果你想迭代'tree'中的所有元素,你真的需要一个使用rapidxml first_node()next_sibling()方法的递归算法。