pugixml node_cdata, node_pcdata set_value() invalid characters

1.5k views Asked by At

pugixml seems to be adding invalid characters when I set the value of a node_pcdata. The code is below. What I'm trying to do is base-64 encode a PNG and send it via XML. I wrote the base-64 encoded text to a file to check it separately from pugixml, and it looks good, ending with these valid characters 4AAAAASUVORK5CYII=. But the ndAvatarData.set_value(avatarEnc) call is adding invalid characters for the same run 4AAAAASUVORK5CYII= cY 3XA+Рz. Occasionally the result is valid, but I have not been able to repeat that, so I don't know what the pugi output looks like in that case.

Is there something I need to do here? Is this a known problem with pugixml? I searched but could not find anything discussing this problem.

I'm getting this in Visual C++ 2010.

char* avatarEnc = NULL;
try {
    std::ifstream avatarIn("MyAvatar.png", std::ios_base::in | std::ios_base::binary);
    if (!avatarIn.is_open())
        cerr << "Could not open avatar file!";
    else {
        base64::encoder E;
        stringstream  avatarOut;
        E.encode(avatarIn, avatarOut);

        avatarOut.seekg(0, ios::end);
        int avatarEncSize = avatarOut.tellg();
        avatarOut.seekg(0, ios::beg);

        avatarEnc = new char[avatarEncSize];
        avatarOut.read(avatarEnc, avatarEncSize);

        std::ofstream tempOut("avatarEnc.txt", std::ios_base::out | std::ios_base::binary);
        tempOut.write(avatarEnc, avatarEncSize);

        xml_node ndAvatar = root.append_child("avatar");
        xml_node ndAvatarData = ndAvatar.append_child(pugi::node_pcdata);
        ndAvatarData.set_value(avatarEnc);
    }
}
catch (...) {
    cerr << "Error loading avatar.";
}
1

There are 1 answers

0
Tomas On BEST ANSWER

Figured it out - set_value() wants a null-terminated string.

avatarEnc = new char[avatarEncSize+1];

avatarOut.read(avatarEnc, avatarEncSize);

avatarEnc[avatarEncSize] = 0;