c++tinyxml2

tinyxml cannot parse const char* correctly


I use tinyxml2 to deal with a string that contains xml. I use the function Parse but it just read a part of the string and return XML_SUCCESS

#include "XML/include/tinyxml2.h"
#include <string>
#include <iostream>

int main(int argc, char* argv[])
{
    std::string xml("<application> <name>something</name> </application>");

    tinyxml2::XMLDocument xmlDoc;
    if (tinyxml2::XML_SUCCESS == xmlDoc.Parse(xml.c_str(), xml.size()))
    {
        tinyxml2::XMLElement* pNode = xmlDoc.FirstChildElement("name");
        std::cout << pNode->GetText() << std::endl;
    }

    return 0;
}

It will throw a exception that tell me the pNode is a nullptr and I checked the _charBuffer of the xmlDoc.

It just contain

<application

Solution

  • I find the question is that xmlDoc do not contain "name". It's the "application" contains the "name"

    tinyxml2::XMLElement* pRoot = xmlDoc.RootElement();
    tinyxml2::XMLElement* pNode = pRoot->FirstChildElement("name");