Question

I'm trying to parse a xml file:

<?xml version="1.0"?>
<settings>
    <output>test.dat</output>
    <width>5</width>
    <depth>4</depth>
    <height>10</height>
</settings>

main:

int _tmain(int argc, wchar_t* argv[])
{
    std::string SettingsFile = "settings.xml";
    rapidxml::xml_document<> doc;
    char* settings = FileHandler::readFileInChar(SettingsFile.c_str());

    std::cout << strlen(settings); // Output 1
    doc.parse<0 | rapidxml::parse_no_data_nodes>(settings);
    std::cout << strlen(settings); // Output 2

    ....
}

Output1: 129

Output2: 31

helper functions:

static char* readFileInChar(const char* p_pccFile) 
{
    char* cpBuffer;
    size_t sSize;

    std::ifstream ifFileToRead;
    ifFileToRead.open(p_pccFile, std::ios::binary);

    if(ifFileToRead.is_open()) {
        sSize = getFileLength(&ifFileToRead);

        cpBuffer = new char[sSize+1];
        ifFileToRead.read(cpBuffer, sSize);
        ifFileToRead.close();
    }

    cpBuffer[sSize] = '\0';

    return cpBuffer;
}

static size_t getFileLength(std::ifstream* file) 
{
    file->seekg(0, std::ios::end);
    size_t length = file->tellg();
    file->seekg(0, std::ios::beg);

    return length;
}

This results in exceptions when I try to access any nodes. I guess I'm missing something obvious here but so far I don't get it.

If I try something like:

std::cout << doc.first_node("output")->value();

I get the message that there has been an access violation while reading position 0x00000004.

Was it helpful?

Solution

The document has no node with the name "output". The document has a node named "settings" which, in turn, has a node named "output". The following code

  std::ifstream file("settings.xml");
  std::vector<char> content = std::vector<char>(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
  content.push_back('\0');

  rapidxml::xml_document<> doc;
  doc.parse<0 | rapidxml::parse_no_data_nodes>(&content[0]);

  rapidxml::xml_node<> * root = doc.first_node();
  for (rapidxml::xml_node<> * node = root->first_node(); node; node = node->next_sibling())
  {
    std::cout << "value of <" << node->name() << "> is " << node->value() << std::endl;
  }

prints

value of <output> is test.dat
value of <width> is 5
value of <depth> is 4
value of <height> is 10

on my machine.

Edit: If you look at "content" in the debugger, you can clearly see where rapidxml inserts '\0' into it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top